blob: 721d337f0866377008e9db58923afab8158c32c5 [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;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080095import static org.mockito.Mockito.reset;
Robin Lee7f5c91c2017-02-08 21:27:02 +000096import static org.mockito.Mockito.timeout;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097import static org.mockito.Mockito.times;
98import static org.mockito.Mockito.verify;
Esteban Talaverab88f42b2017-01-24 16:47:16 +000099import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100import static org.mockito.Mockito.when;
Paul Duffin192bb0b2017-03-09 18:49:41 +0000101import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700102
103/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700104 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000105 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106 m FrameworksServicesTests &&
107 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000108 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800110 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111
112 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000113 *
114 * , or:
115 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000117@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000119 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
120 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
121 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
122
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123 private DpmMockContext mContext;
124 public DevicePolicyManager dpm;
125 public DevicePolicyManagerServiceTestable dpms;
126
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100127 /*
128 * The CA cert below is the content of cacert.pem as generated by:
129 *
130 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
131 */
132 private static final String TEST_CA =
133 "-----BEGIN CERTIFICATE-----\n" +
134 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
135 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
136 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
137 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
138 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
139 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
140 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
141 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
142 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
143 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
144 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
145 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
146 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
147 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
148 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
149 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
150 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
151 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
152 "wQ==\n" +
153 "-----END CERTIFICATE-----\n";
154
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700155 @Override
156 protected void setUp() throws Exception {
157 super.setUp();
158
159 mContext = getContext();
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700160 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
161 .thenReturn(true);
162
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800163 // By default, pretend all users are running and unlocked.
164 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
165
Makoto Onukia52562c2015-10-01 16:12:31 -0700166 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700167
Makoto Onukid932f762015-09-29 16:53:38 -0700168 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
169 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
170 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800171 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700172
Makoto Onukib643fb02015-09-22 15:03:44 -0700173 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700174 }
175
Robin Lee2c68dad2017-03-17 12:50:24 +0000176 @Override
177 protected void tearDown() throws Exception {
178 flushTasks();
179 super.tearDown();
180 }
181
Makoto Onukia52562c2015-10-01 16:12:31 -0700182 private void initializeDpms() {
183 // Need clearCallingIdentity() to pass permission checks.
184 final long ident = mContext.binder.clearCallingIdentity();
185 try {
186 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
187
188 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
189
190 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
191 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
192
193 dpm = new DevicePolicyManagerTestable(mContext, dpms);
194 } finally {
195 mContext.binder.restoreCallingIdentity(ident);
196 }
197 }
198
Makoto Onukib643fb02015-09-22 15:03:44 -0700199 private void setUpUserManager() {
200 // Emulate UserManager.set/getApplicationRestriction().
201 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
202
203 // UM.setApplicationRestrictions() will save to appRestrictions.
204 doAnswer(new Answer<Void>() {
205 @Override
206 public Void answer(InvocationOnMock invocation) throws Throwable {
207 String pkg = (String) invocation.getArguments()[0];
208 Bundle bundle = (Bundle) invocation.getArguments()[1];
209 UserHandle user = (UserHandle) invocation.getArguments()[2];
210
211 appRestrictions.put(Pair.create(pkg, user), bundle);
212
213 return null;
214 }
215 }).when(mContext.userManager).setApplicationRestrictions(
216 anyString(), any(Bundle.class), any(UserHandle.class));
217
218 // UM.getApplicationRestrictions() will read from appRestrictions.
219 doAnswer(new Answer<Bundle>() {
220 @Override
221 public Bundle answer(InvocationOnMock invocation) throws Throwable {
222 String pkg = (String) invocation.getArguments()[0];
223 UserHandle user = (UserHandle) invocation.getArguments()[1];
224
225 return appRestrictions.get(Pair.create(pkg, user));
226 }
227 }).when(mContext.userManager).getApplicationRestrictions(
228 anyString(), any(UserHandle.class));
229
Makoto Onukid932f762015-09-29 16:53:38 -0700230 // Add the first secondary user.
231 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700232 }
233
234 private void setAsProfileOwner(ComponentName admin) {
235 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
236 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
237
Makoto Onukia4f11972015-10-01 13:19:58 -0700238 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700239 dpm.setActiveAdmin(admin, /* replace =*/ false);
240
241 // Fire!
242 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
243
244 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700245 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700246 }
247
248 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700249 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
250 .thenReturn(false);
251
252 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
253 new DevicePolicyManagerServiceTestable(mContext, dataDir);
254
255 // If the device has no DPMS feature, it shouldn't register the local service.
256 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
257 }
258
259 /**
260 * Caller doesn't have proper permissions.
261 */
262 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700263 // 1. Failure cases.
264
265 // Caller doesn't have MANAGE_DEVICE_ADMINS.
266 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700267 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700268 fail("Didn't throw SecurityException");
269 } catch (SecurityException expected) {
270 }
271
272 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
273 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
274 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700275 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700276 fail("Didn't throw SecurityException");
277 } catch (SecurityException expected) {
278 }
279 }
280
Makoto Onukif76b06a2015-09-22 15:03:44 -0700281 /**
282 * Test for:
283 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800284 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700285 * {@link DevicePolicyManager#isAdminActive}
286 * {@link DevicePolicyManager#isAdminActiveAsUser}
287 * {@link DevicePolicyManager#getActiveAdmins}
288 * {@link DevicePolicyManager#getActiveAdminsAsUser}
289 */
290 public void testSetActiveAdmin() throws Exception {
291 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700292 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
293
Makoto Onukif76b06a2015-09-22 15:03:44 -0700294 // 2. Call the API.
295 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700296
297 // 3. Verify internal calls.
298
299 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700300 verify(mContext.spiedContext).sendBroadcastAsUser(
301 MockUtils.checkIntentAction(
302 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
303 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
304 verify(mContext.spiedContext).sendBroadcastAsUser(
305 MockUtils.checkIntentAction(
306 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700307 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
308
Makoto Onukif76b06a2015-09-22 15:03:44 -0700309 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
310 eq(admin1.getPackageName()),
311 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
312 eq(PackageManager.DONT_KILL_APP),
313 eq(DpmMockContext.CALLER_USER_HANDLE),
314 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700315
316 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700317
318 // Make sure it's active admin1.
319 assertTrue(dpm.isAdminActive(admin1));
320 assertFalse(dpm.isAdminActive(admin2));
321 assertFalse(dpm.isAdminActive(admin3));
322
323 // But not admin1 for a different user.
324
325 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
326 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
327 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
328
329 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
330 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
331
332 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
333
334 // Next, add one more admin.
335 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700336 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
337 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700338
339 dpm.setActiveAdmin(admin2, /* replace =*/ false);
340
341 // Now we have two admins.
342 assertTrue(dpm.isAdminActive(admin1));
343 assertTrue(dpm.isAdminActive(admin2));
344 assertFalse(dpm.isAdminActive(admin3));
345
346 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
347 // again. (times(1) because it was previously called for admin1)
348 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
349 eq(admin1.getPackageName()),
350 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
351 eq(PackageManager.DONT_KILL_APP),
352 eq(DpmMockContext.CALLER_USER_HANDLE),
353 anyString());
354
355 // 4. Add the same admin1 again without replace, which should throw.
356 try {
357 dpm.setActiveAdmin(admin1, /* replace =*/ false);
358 fail("Didn't throw");
359 } catch (IllegalArgumentException expected) {
360 }
361
362 // 5. Add the same admin1 again with replace, which should succeed.
363 dpm.setActiveAdmin(admin1, /* replace =*/ true);
364
365 // TODO make sure it's replaced.
366
367 // 6. Test getActiveAdmins()
368 List<ComponentName> admins = dpm.getActiveAdmins();
369 assertEquals(2, admins.size());
370 assertEquals(admin1, admins.get(0));
371 assertEquals(admin2, admins.get(1));
372
373 // Another user has no admins.
374 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
375
376 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
377 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
378
379 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
380 }
381
Makoto Onukid932f762015-09-29 16:53:38 -0700382 public void testSetActiveAdmin_multiUsers() throws Exception {
383
384 final int ANOTHER_USER_ID = 100;
385 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
386
387 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
388
389 // Set up pacakge manager for the other user.
390 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700391
392 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
393
394 dpm.setActiveAdmin(admin1, /* replace =*/ false);
395
396 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
397 dpm.setActiveAdmin(admin2, /* replace =*/ false);
398
399
400 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
401 assertTrue(dpm.isAdminActive(admin1));
402 assertFalse(dpm.isAdminActive(admin2));
403
404 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
405 assertFalse(dpm.isAdminActive(admin1));
406 assertTrue(dpm.isAdminActive(admin2));
407 }
408
Makoto Onukif76b06a2015-09-22 15:03:44 -0700409 /**
410 * Test for:
411 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800412 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700413 */
414 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
415 // 1. Make sure the caller has proper permissions.
416 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
417
418 dpm.setActiveAdmin(admin1, /* replace =*/ false);
419 assertTrue(dpm.isAdminActive(admin1));
420
421 // Add the same admin1 again without replace, which should throw.
422 try {
423 dpm.setActiveAdmin(admin1, /* replace =*/ false);
424 fail("Didn't throw");
425 } catch (IllegalArgumentException expected) {
426 }
427 }
428
429 /**
430 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800431 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
432 * BIND_DEVICE_ADMIN.
433 */
434 public void testSetActiveAdmin_permissionCheck() throws Exception {
435 // 1. Make sure the caller has proper permissions.
436 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
437
438 try {
439 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
440 fail();
441 } catch (IllegalArgumentException expected) {
442 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
443 }
444 assertFalse(dpm.isAdminActive(adminNoPerm));
445
446 // Change the target API level to MNC. Now it can be set as DA.
447 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
448 VERSION_CODES.M);
449 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
450 assertTrue(dpm.isAdminActive(adminNoPerm));
451
452 // TODO Test the "load from the file" case where DA will still be loaded even without
453 // BIND_DEVICE_ADMIN and target API is N.
454 }
455
456 /**
457 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700458 * {@link DevicePolicyManager#removeActiveAdmin}
459 */
460 public void testRemoveActiveAdmin_SecurityException() {
461 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
462
463 // Add admin.
464
465 dpm.setActiveAdmin(admin1, /* replace =*/ false);
466
467 assertTrue(dpm.isAdminActive(admin1));
468
469 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
470
471 // Directly call the DPMS method with a different userid, which should fail.
472 try {
473 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
474 fail("Didn't throw SecurityException");
475 } catch (SecurityException expected) {
476 }
477
478 // Try to remove active admin with a different caller userid should fail too, without
479 // having MANAGE_DEVICE_ADMINS.
480 mContext.callerPermissions.clear();
481
Makoto Onukid932f762015-09-29 16:53:38 -0700482 // Change the caller, and call into DPMS directly with a different user-id.
483
Makoto Onukif76b06a2015-09-22 15:03:44 -0700484 mContext.binder.callingUid = 1234567;
485 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700486 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700487 fail("Didn't throw SecurityException");
488 } catch (SecurityException expected) {
489 }
490 }
491
492 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800493 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
494 * (because we can't send the remove broadcast).
495 */
496 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
497 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
498
499 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
500
501 // Add admin.
502
503 dpm.setActiveAdmin(admin1, /* replace =*/ false);
504
505 assertTrue(dpm.isAdminActive(admin1));
506
507 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
508
509 // 1. User not unlocked.
510 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
511 .thenReturn(false);
512 try {
513 dpm.removeActiveAdmin(admin1);
514 fail("Didn't throw IllegalStateException");
515 } catch (IllegalStateException expected) {
516 MoreAsserts.assertContainsRegex(
517 "User must be running and unlocked", expected.getMessage());
518 }
519
520 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
521
522 // 2. User unlocked.
523 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
524 .thenReturn(true);
525
526 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700527 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800528 }
529
530 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700531 * Test for:
532 * {@link DevicePolicyManager#removeActiveAdmin}
533 */
Makoto Onukid932f762015-09-29 16:53:38 -0700534 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
536
537 // Add admin1.
538
539 dpm.setActiveAdmin(admin1, /* replace =*/ false);
540
541 assertTrue(dpm.isAdminActive(admin1));
542 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
543
544 // Different user, but should work, because caller has proper permissions.
545 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700546
547 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700548 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700549
550 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700551 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700552
553 // TODO DO Still can't be removed in this case.
554 }
555
556 /**
557 * Test for:
558 * {@link DevicePolicyManager#removeActiveAdmin}
559 */
560 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
561 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
562 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
563
564 // Add admin1.
565
566 dpm.setActiveAdmin(admin1, /* replace =*/ false);
567
568 assertTrue(dpm.isAdminActive(admin1));
569 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
570
571 // Broadcast from saveSettingsLocked().
572 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
573 MockUtils.checkIntentAction(
574 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
575 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
576
577 // Remove. No permissions, but same user, so it'll work.
578 mContext.callerPermissions.clear();
579 dpm.removeActiveAdmin(admin1);
580
Makoto Onukif76b06a2015-09-22 15:03:44 -0700581 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
582 MockUtils.checkIntentAction(
583 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
584 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
585 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700586 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700587 eq(dpms.mHandler),
588 eq(Activity.RESULT_OK),
589 isNull(String.class),
590 isNull(Bundle.class));
591
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700592 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700593
594 // Again broadcast from saveSettingsLocked().
595 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
596 MockUtils.checkIntentAction(
597 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
598 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
599
600 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700601 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700602
603 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000604 * Test for: @{link DevicePolicyManager#setActivePasswordState}
605 *
606 * Validates that when the password for a user changes, the notification broadcast intent
607 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
608 * addition to ones in the original user.
609 */
610 public void testSetActivePasswordState_sendToProfiles() throws Exception {
611 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
612
613 final int MANAGED_PROFILE_USER_ID = 78;
614 final int MANAGED_PROFILE_ADMIN_UID =
615 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
616
617 // Setup device owner.
618 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
619 mContext.packageName = admin1.getPackageName();
620 setupDeviceOwner();
621
622 // Add a managed profile belonging to the system user.
623 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
624
625 // Change the parent user's password.
626 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
627
628 // Both the device owner and the managed profile owner should receive this broadcast.
629 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
630 intent.setComponent(admin1);
631 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
632
633 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
634 MockUtils.checkIntent(intent),
635 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
636 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
637 MockUtils.checkIntent(intent),
638 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
639 }
640
641 /**
642 * Test for: @{link DevicePolicyManager#setActivePasswordState}
643 *
644 * Validates that when the password for a managed profile changes, the notification broadcast
645 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
646 * its parent.
647 */
648 public void testSetActivePasswordState_notSentToParent() throws Exception {
649 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
650
651 final int MANAGED_PROFILE_USER_ID = 78;
652 final int MANAGED_PROFILE_ADMIN_UID =
653 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
654
655 // Setup device owner.
656 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
657 mContext.packageName = admin1.getPackageName();
658 doReturn(true).when(mContext.lockPatternUtils)
659 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
660 setupDeviceOwner();
661
662 // Add a managed profile belonging to the system user.
663 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
664
665 // Change the profile's password.
666 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
667
668 // Both the device owner and the managed profile owner should receive this broadcast.
669 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
670 intent.setComponent(admin1);
671 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
672
673 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
674 MockUtils.checkIntent(intent),
675 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
676 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
677 MockUtils.checkIntent(intent),
678 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
679 }
680 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000681 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700682 */
683 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000684 setDeviceOwner();
685
686 // Try to set a profile owner on the same user, which should fail.
687 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
688 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
689 try {
690 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
691 fail("IllegalStateException not thrown");
692 } catch (IllegalStateException expected) {
693 assertTrue("Message was: " + expected.getMessage(),
694 expected.getMessage().contains("already has a device owner"));
695 }
696
697 // DO admin can't be deactivated.
698 dpm.removeActiveAdmin(admin1);
699 assertTrue(dpm.isAdminActive(admin1));
700
701 // TODO Test getDeviceOwnerName() too. To do so, we need to change
702 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
703 }
704
705 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700706 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800707 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700708 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
709 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
710
Makoto Onukid932f762015-09-29 16:53:38 -0700711 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700712 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
713
Makoto Onukid932f762015-09-29 16:53:38 -0700714 // Make sure admin1 is installed on system user.
715 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700716
Makoto Onukic8a5a552015-11-19 14:29:12 -0800717 // Check various get APIs.
718 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
719
Makoto Onukib643fb02015-09-22 15:03:44 -0700720 // DO needs to be an DA.
721 dpm.setActiveAdmin(admin1, /* replace =*/ false);
722
723 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700724 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700725
Makoto Onukic8a5a552015-11-19 14:29:12 -0800726 // getDeviceOwnerComponent should return the admin1 component.
727 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
728 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
729
730 // Check various get APIs.
731 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
732
733 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
734 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
735 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
736 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
737
738 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
739
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000740 // Verify internal calls.
741 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
742 eq(admin1.getPackageName()));
743
Makoto Onukib643fb02015-09-22 15:03:44 -0700744 // TODO We should check if the caller has called clearCallerIdentity().
745 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
746 eq(UserHandle.USER_SYSTEM), eq(false));
747
748 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
749 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
750 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
751
Makoto Onukic8a5a552015-11-19 14:29:12 -0800752 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700753 }
754
Makoto Onukic8a5a552015-11-19 14:29:12 -0800755 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
756 final int origCallingUser = mContext.binder.callingUid;
757 final List origPermissions = new ArrayList(mContext.callerPermissions);
758 mContext.callerPermissions.clear();
759
760 mContext.callerPermissions.add(permission.MANAGE_USERS);
761
762 mContext.binder.callingUid = Process.SYSTEM_UID;
763
764 // TODO Test getDeviceOwnerName() too. To do so, we need to change
765 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
766 if (hasDeviceOwner) {
767 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
768 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
769 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
770
771 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
772 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
773 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
774 } else {
775 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
776 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
777 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
778
779 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
780 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
781 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
782 }
783
784 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
785 if (hasDeviceOwner) {
786 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
787 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
788 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
789
790 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
791 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
792 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
793 } else {
794 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
795 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
796 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
797
798 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
799 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
800 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
801 }
802
803 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
804 // Still with MANAGE_USERS.
805 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
806 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
807 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
808
809 if (hasDeviceOwner) {
810 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
811 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
812 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
813 } else {
814 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
815 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
816 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
817 }
818
819 mContext.binder.callingUid = Process.SYSTEM_UID;
820 mContext.callerPermissions.remove(permission.MANAGE_USERS);
821 // System can still call "OnAnyUser" without MANAGE_USERS.
822 if (hasDeviceOwner) {
823 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
824 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
825 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
826
827 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
828 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
829 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
830 } else {
831 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
832 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
833 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
834
835 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
836 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
837 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
838 }
839
840 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
841 // Still no MANAGE_USERS.
842 if (hasDeviceOwner) {
843 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
844 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
845 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
846 } else {
847 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
848 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
849 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
850 }
851
852 try {
853 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
854 fail();
855 } catch (SecurityException expected) {
856 }
857 try {
858 dpm.getDeviceOwnerComponentOnAnyUser();
859 fail();
860 } catch (SecurityException expected) {
861 }
862 try {
863 dpm.getDeviceOwnerUserId();
864 fail();
865 } catch (SecurityException expected) {
866 }
867 try {
868 dpm.getDeviceOwnerNameOnAnyUser();
869 fail();
870 } catch (SecurityException expected) {
871 }
872
873 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
874 // Still no MANAGE_USERS.
875 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
876 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
877 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
878
879 try {
880 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
881 fail();
882 } catch (SecurityException expected) {
883 }
884 try {
885 dpm.getDeviceOwnerComponentOnAnyUser();
886 fail();
887 } catch (SecurityException expected) {
888 }
889 try {
890 dpm.getDeviceOwnerUserId();
891 fail();
892 } catch (SecurityException expected) {
893 }
894 try {
895 dpm.getDeviceOwnerNameOnAnyUser();
896 fail();
897 } catch (SecurityException expected) {
898 }
899
900 // Restore.
901 mContext.binder.callingUid = origCallingUser;
902 mContext.callerPermissions.addAll(origPermissions);
903 }
904
905
Makoto Onukib643fb02015-09-22 15:03:44 -0700906 /**
907 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
908 */
909 public void testSetDeviceOwner_noSuchPackage() {
910 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800911 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700912 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
913 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
914
915 // Call from a process on the system user.
916 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
917
Makoto Onukib643fb02015-09-22 15:03:44 -0700918 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700919 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700920 fail("Didn't throw IllegalArgumentException");
921 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700922 assertTrue("Message was: " + expected.getMessage(),
923 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700924 }
925 }
926
927 public void testSetDeviceOwner_failures() throws Exception {
928 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
929 }
930
Makoto Onukia52562c2015-10-01 16:12:31 -0700931 public void testClearDeviceOwner() throws Exception {
932 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800933 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700934 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
935 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
936
937 // Set admin1 as a DA to the secondary user.
938 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
939
940 dpm.setActiveAdmin(admin1, /* replace =*/ false);
941
942 // Set admin 1 as the DO to the system user.
943
944 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
945 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
946 dpm.setActiveAdmin(admin1, /* replace =*/ false);
947 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
948
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000949 // Verify internal calls.
950 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
951 eq(admin1.getPackageName()));
952
Makoto Onukic8a5a552015-11-19 14:29:12 -0800953 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700954
Makoto Onuki90b89652016-01-28 14:44:18 -0800955 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Victor Chang348f6962017-01-30 16:19:13 +0000956 when(mContext.userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
957 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800958
959 assertTrue(dpm.isAdminActive(admin1));
960 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
961
Makoto Onukia52562c2015-10-01 16:12:31 -0700962 // Set up other mocks.
963 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
964
965 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700966 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700967 eq(admin1.getPackageName()),
968 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800969
970 // But first pretend the user is locked. Then it should fail.
971 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
972 try {
973 dpm.clearDeviceOwnerApp(admin1.getPackageName());
974 fail("Didn't throw IllegalStateException");
975 } catch (IllegalStateException expected) {
976 MoreAsserts.assertContainsRegex(
977 "User must be running and unlocked", expected.getMessage());
978 }
979
980 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800981 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700982 dpm.clearDeviceOwnerApp(admin1.getPackageName());
983
984 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800985 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700986
Victor Chang348f6962017-01-30 16:19:13 +0000987 verify(mContext.userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
988 eq(false),
989 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
990
Makoto Onuki90b89652016-01-28 14:44:18 -0800991 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
992 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100993 eq(null),
994 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800995
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700996 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100997
998 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
999 // and once for clearing it.
1000 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1001 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1002 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001003 // TODO Check other calls.
1004 }
1005
1006 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1007 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001008 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001009 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1010 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1011
1012 // Set admin1 as a DA to the secondary user.
1013 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1014
1015 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1016
1017 // Set admin 1 as the DO to the system user.
1018
1019 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1020 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1021 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1022 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1023
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001024 // Verify internal calls.
1025 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
1026 eq(admin1.getPackageName()));
1027
Makoto Onukic8a5a552015-11-19 14:29:12 -08001028 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001029
1030 // Now call clear from the secondary user, which should throw.
1031 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1032
1033 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001034 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001035 eq(admin1.getPackageName()),
1036 anyInt());
1037 try {
1038 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1039 fail("Didn't throw");
1040 } catch (SecurityException e) {
1041 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1042 }
1043
Makoto Onukic8a5a552015-11-19 14:29:12 -08001044 // DO shouldn't be removed.
1045 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001046 }
1047
Makoto Onukib643fb02015-09-22 15:03:44 -07001048 public void testSetProfileOwner() throws Exception {
1049 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001050
Makoto Onuki90b89652016-01-28 14:44:18 -08001051 // PO admin can't be deactivated.
1052 dpm.removeActiveAdmin(admin1);
1053 assertTrue(dpm.isAdminActive(admin1));
1054
Makoto Onuki803d6752015-10-30 12:58:39 -07001055 // Try setting DO on the same user, which should fail.
1056 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1057 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1058 try {
1059 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1060 fail("IllegalStateException not thrown");
1061 } catch (IllegalStateException expected) {
1062 assertTrue("Message was: " + expected.getMessage(),
1063 expected.getMessage().contains("already has a profile owner"));
1064 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001065 }
1066
Makoto Onuki90b89652016-01-28 14:44:18 -08001067 public void testClearProfileOwner() throws Exception {
1068 setAsProfileOwner(admin1);
1069
1070 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1071
1072 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1073 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1074
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001075 // First try when the user is locked, which should fail.
1076 when(mContext.userManager.isUserUnlocked(anyInt()))
1077 .thenReturn(false);
1078 try {
1079 dpm.clearProfileOwner(admin1);
1080 fail("Didn't throw IllegalStateException");
1081 } catch (IllegalStateException expected) {
1082 MoreAsserts.assertContainsRegex(
1083 "User must be running and unlocked", expected.getMessage());
1084 }
1085 // Clear, really.
1086 when(mContext.userManager.isUserUnlocked(anyInt()))
1087 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001088 dpm.clearProfileOwner(admin1);
1089
1090 // Check
1091 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001092 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001093 }
1094
Makoto Onukib643fb02015-09-22 15:03:44 -07001095 public void testSetProfileOwner_failures() throws Exception {
1096 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1097 }
1098
Makoto Onukia52562c2015-10-01 16:12:31 -07001099 public void testGetDeviceOwnerAdminLocked() throws Exception {
1100 checkDeviceOwnerWithMultipleDeviceAdmins();
1101 }
1102
1103 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1104 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1105 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1106 // make sure it gets the right component from the right user.
1107
1108 final int ANOTHER_USER_ID = 100;
1109 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1110
1111 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1112
1113 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001114 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001115 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1116 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1117
1118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1119
Victor Change29cd472016-03-02 20:57:42 +00001120 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1121
Makoto Onukia52562c2015-10-01 16:12:31 -07001122 // Make sure the admin packge is installed to each user.
1123 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1124 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1125
1126 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1127 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1128
1129 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1130
1131
1132 // Set active admins to the users.
1133 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1134 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1135
1136 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1137 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1138
1139 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1140
1141 // Set DO on the first non-system user.
1142 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1143 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1144
Makoto Onukic8a5a552015-11-19 14:29:12 -08001145 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001146
1147 // Then check getDeviceOwnerAdminLocked().
1148 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1149 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1150 }
1151
1152 /**
1153 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001154 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1155 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001156 *
1157 * We didn't use to persist the DO component class name, but now we do, and the above method
1158 * finds the right component from a package name upon migration.
1159 */
1160 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001161 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001162 checkDeviceOwnerWithMultipleDeviceAdmins();
1163
1164 // Overwrite the device owner setting and clears the clas name.
1165 dpms.mOwners.setDeviceOwner(
1166 new ComponentName(admin2.getPackageName(), ""),
1167 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1168 dpms.mOwners.writeDeviceOwner();
1169
1170 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001171 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001172
1173 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001174 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1175 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001176 initializeDpms();
1177
1178 // Now the DO component name is a full name.
1179 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1180 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001181 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001182 }
1183
Makoto Onukib643fb02015-09-22 15:03:44 -07001184 public void testSetGetApplicationRestriction() {
1185 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001186 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001187
1188 {
1189 Bundle rest = new Bundle();
1190 rest.putString("KEY_STRING", "Foo1");
1191 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1192 }
1193
1194 {
1195 Bundle rest = new Bundle();
1196 rest.putString("KEY_STRING", "Foo2");
1197 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1198 }
1199
1200 {
1201 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1202 assertNotNull(returned);
1203 assertEquals(returned.size(), 1);
1204 assertEquals(returned.get("KEY_STRING"), "Foo1");
1205 }
1206
1207 {
1208 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1209 assertNotNull(returned);
1210 assertEquals(returned.size(), 1);
1211 assertEquals(returned.get("KEY_STRING"), "Foo2");
1212 }
1213
1214 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1215 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1216 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001217
Edman Anjosf9946772016-11-28 16:35:15 +01001218 /**
1219 * Setup a package in the package manager mock. Useful for faking installed applications.
1220 *
1221 * @param packageName the name of the package to be setup
1222 * @param appId the application ID to be given to the package
1223 * @return the UID of the package as known by the mock package manager
1224 */
1225 private int setupPackageInPackageManager(final String packageName, final int appId)
1226 throws Exception {
1227 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1228 final PackageInfo pi = new PackageInfo();
1229 pi.applicationInfo = new ApplicationInfo();
1230 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1231 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1232 eq(packageName),
1233 anyInt(),
1234 eq(DpmMockContext.CALLER_USER_HANDLE));
1235 // Setup application UID with the PackageManager
1236 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1237 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1238 eq(packageName),
1239 eq(DpmMockContext.CALLER_USER_HANDLE));
1240 // Associate packageName to uid
1241 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1242 doReturn(new String[]{packageName})
1243 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1244 return uid;
1245 }
1246
Robin Lee7f5c91c2017-02-08 21:27:02 +00001247 public void testCertificateDisclosure() throws Exception {
1248 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1249 final UserHandle user = UserHandle.of(userId);
1250
1251 mContext.applicationInfo = new ApplicationInfo();
1252 mContext.callerPermissions.add(permission.MANAGE_USERS);
1253 mContext.packageName = "com.android.frameworks.servicestests";
Robin Lee2c68dad2017-03-17 12:50:24 +00001254 mContext.addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001255 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1256
Robin Leeabaa0692017-02-20 20:54:22 +00001257 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1258 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001259
1260 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1261 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1262
1263 // Given that we have exactly one certificate installed,
1264 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1265 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001266 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001267 // a notification should not be shown.
1268 verify(mContext.notificationManager, timeout(1000))
1269 .cancelAsUser(anyString(), anyInt(), eq(user));
1270
1271 // Given that we have four certificates installed,
1272 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1273 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001274 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1275 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001276 // a notification should be shown saying that there are two certificates left to approve.
1277 verify(mContext.notificationManager, timeout(1000))
1278 .notifyAsUser(anyString(), anyInt(), argThat(
1279 new BaseMatcher<Notification>() {
1280 @Override
1281 public boolean matches(Object item) {
1282 final Notification noti = (Notification) item;
1283 return TEST_STRING.equals(
1284 noti.extras.getString(Notification.EXTRA_TITLE));
1285 }
1286 @Override
1287 public void describeTo(Description description) {
1288 description.appendText(
1289 "Notification{title=\"" + TEST_STRING + "\"}");
1290 }
1291 }), eq(user));
1292 }
1293
Edman Anjosf9946772016-11-28 16:35:15 +01001294 /**
1295 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1296 * privileges can acually be exercised by a delegate are not covered here.
1297 */
1298 public void testDelegation() throws Exception {
1299 setAsProfileOwner(admin1);
1300
1301 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1302
1303 // Given two packages
1304 final String CERT_DELEGATE = "com.delegate.certs";
1305 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1306 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1307 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1308 20989);
1309
1310 // On delegation
1311 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1312 mContext.packageName = admin1.getPackageName();
1313 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1314 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1315
1316 // DPMS correctly stores and retrieves the delegates
1317 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1318 assertEquals(2, policy.mDelegationMap.size());
1319 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1320 DELEGATION_CERT_INSTALL);
1321 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1322 DELEGATION_CERT_INSTALL);
1323 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1324 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1325 DELEGATION_APP_RESTRICTIONS);
1326 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1327 DELEGATION_APP_RESTRICTIONS);
1328 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1329
1330 // On calling install certificate APIs from an unauthorized process
1331 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1332 mContext.packageName = RESTRICTIONS_DELEGATE;
1333
1334 // DPMS throws a SecurityException
1335 try {
1336 dpm.installCaCert(null, null);
1337 fail("Didn't throw SecurityException on unauthorized access");
1338 } catch (SecurityException expected) {
1339 }
1340
1341 // On calling install certificate APIs from an authorized process
1342 mContext.binder.callingUid = CERT_DELEGATE_UID;
1343 mContext.packageName = CERT_DELEGATE;
1344
1345 // DPMS executes without a SecurityException
1346 try {
1347 dpm.installCaCert(null, null);
1348 } catch (SecurityException unexpected) {
1349 fail("Threw SecurityException on authorized access");
1350 } catch (NullPointerException expected) {
1351 }
1352
1353 // On removing a delegate
1354 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1355 mContext.packageName = admin1.getPackageName();
1356 dpm.setCertInstallerPackage(admin1, null);
1357
1358 // DPMS does not allow access to ex-delegate
1359 mContext.binder.callingUid = CERT_DELEGATE_UID;
1360 mContext.packageName = CERT_DELEGATE;
1361 try {
1362 dpm.installCaCert(null, null);
1363 fail("Didn't throw SecurityException on unauthorized access");
1364 } catch (SecurityException expected) {
1365 }
1366
1367 // But still allows access to other existing delegates
1368 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1369 mContext.packageName = RESTRICTIONS_DELEGATE;
1370 try {
1371 dpm.getApplicationRestrictions(null, "pkg");
1372 } catch (SecurityException expected) {
1373 fail("Threw SecurityException on authorized access");
1374 }
1375 }
1376
Esteban Talaverabf60f722015-12-10 16:26:44 +00001377 public void testApplicationRestrictionsManagingApp() throws Exception {
1378 setAsProfileOwner(admin1);
1379
Rubin Xued1928a2016-02-11 17:23:06 +00001380 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001381 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1382 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001383 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1384 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001385
Esteban Talaverabf60f722015-12-10 16:26:44 +00001386 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1387 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001388 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1389 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001390 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1391 Bundle rest = new Bundle();
1392 rest.putString("KEY_STRING", "Foo1");
1393 try {
1394 dpm.setApplicationRestrictions(null, "pkg1", rest);
1395 fail("Didn't throw expected SecurityException");
1396 } catch (SecurityException expected) {
1397 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001398 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1399 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001400 }
1401 try {
1402 dpm.getApplicationRestrictions(null, "pkg1");
1403 fail("Didn't throw expected SecurityException");
1404 } catch (SecurityException expected) {
1405 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001406 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1407 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001408 }
1409
1410 // Check via the profile owner that no restrictions were set.
1411 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001412 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001413 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1414
Rubin Xued1928a2016-02-11 17:23:06 +00001415 // Check the API does not allow setting a non-existent package
1416 try {
1417 dpm.setApplicationRestrictionsManagingPackage(admin1,
1418 nonExistAppRestrictionsManagerPackage);
1419 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001420 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001421 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001422 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001423 }
1424
Esteban Talaverabf60f722015-12-10 16:26:44 +00001425 // Let appRestrictionsManagerPackage manage app restrictions
1426 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1427 assertEquals(appRestrictionsManagerPackage,
1428 dpm.getApplicationRestrictionsManagingPackage(admin1));
1429
1430 // Now that package should be able to set and retrieve app restrictions.
1431 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001432 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001433 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1434 dpm.setApplicationRestrictions(null, "pkg1", rest);
1435 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1436 assertEquals(1, returned.size(), 1);
1437 assertEquals("Foo1", returned.get("KEY_STRING"));
1438
1439 // The same app running on a separate user shouldn't be able to manage app restrictions.
1440 mContext.binder.callingUid = UserHandle.getUid(
1441 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1442 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1443 try {
1444 dpm.setApplicationRestrictions(null, "pkg1", rest);
1445 fail("Didn't throw expected SecurityException");
1446 } catch (SecurityException expected) {
1447 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001448 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1449 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001450 }
1451
1452 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1453 // too.
1454 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001455 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001456 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1457 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1458 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1459
1460 // Removing the ability for the package to manage app restrictions.
1461 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1462 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1463 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001464 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001465 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1466 try {
1467 dpm.setApplicationRestrictions(null, "pkg1", null);
1468 fail("Didn't throw expected SecurityException");
1469 } catch (SecurityException expected) {
1470 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001471 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1472 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001473 }
1474 }
1475
Makoto Onukia4f11972015-10-01 13:19:58 -07001476 public void testSetUserRestriction_asDo() throws Exception {
1477 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001478 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001479 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1480 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1481
1482 // First, set DO.
1483
1484 // Call from a process on the system user.
1485 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1486
1487 // Make sure admin1 is installed on system user.
1488 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001489
1490 // Call.
1491 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001492 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001493 UserHandle.USER_SYSTEM));
1494
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001495 // Check that the user restrictions that are enabled by default are set. Then unset them.
1496 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001497 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001498 DpmTestUtils.assertRestrictions(
1499 DpmTestUtils.newRestrictions(defaultRestrictions),
1500 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1501 );
1502 DpmTestUtils.assertRestrictions(
1503 DpmTestUtils.newRestrictions(defaultRestrictions),
1504 dpm.getUserRestrictions(admin1)
1505 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001506 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1507 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001508 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001509 eq(true) /* isDeviceOwner */,
1510 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001511 );
1512 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001513
1514 for (String restriction : defaultRestrictions) {
1515 dpm.clearUserRestriction(admin1, restriction);
1516 }
1517
Esteban Talavera548a04b2016-12-20 15:22:30 +00001518 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001519 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001520
1521 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1522 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1523 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001524 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1525 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001526 reset(mContext.userManagerInternal);
1527
Makoto Onukia4f11972015-10-01 13:19:58 -07001528 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1530 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001531 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1532 UserManager.DISALLOW_ADD_USER),
1533 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001535
Makoto Onuki068c54a2015-10-13 14:34:03 -07001536 DpmTestUtils.assertRestrictions(
1537 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001539 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1540 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001541 DpmTestUtils.assertRestrictions(
1542 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001543 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001544 dpm.getUserRestrictions(admin1)
1545 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001546
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1548 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1549 eq(UserHandle.USER_SYSTEM),
1550 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001551 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001552 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001553
Makoto Onuki068c54a2015-10-13 14:34:03 -07001554 DpmTestUtils.assertRestrictions(
1555 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1556 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1557 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001558 DpmTestUtils.assertRestrictions(
1559 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1560 dpm.getUserRestrictions(admin1)
1561 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001562
1563 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001564 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1565 eq(UserHandle.USER_SYSTEM),
1566 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001567 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001569
Esteban Talavera548a04b2016-12-20 15:22:30 +00001570 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001571
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1573 // DO sets them, the scope is global.
1574 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1575 reset(mContext.userManagerInternal);
1576 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1577 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1578 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001580 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1581 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001582 reset(mContext.userManagerInternal);
1583
1584 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1585 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001586 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001587
1588 // More tests.
1589 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1590 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1591 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001592 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1593 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001594 reset(mContext.userManagerInternal);
1595
1596 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1597 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1598 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001599 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001600 UserManager.DISALLOW_ADD_USER),
1601 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602 reset(mContext.userManagerInternal);
1603
1604 dpm.setCameraDisabled(admin1, true);
1605 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1606 eq(UserHandle.USER_SYSTEM),
1607 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001608 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001609 UserManager.DISALLOW_ADD_USER),
1610 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001611 reset(mContext.userManagerInternal);
1612
1613 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1614 // locally.
1615 dpm.setCameraDisabled(admin1, false);
1616 reset(mContext.userManagerInternal);
1617
1618 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1619 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1620 dpm.setCameraDisabled(admin2, true);
1621
1622 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1623 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001624 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 UserManager.DISALLOW_ADD_USER),
1627 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001628 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001629 // TODO Make sure restrictions are written to the file.
1630 }
1631
1632 public void testSetUserRestriction_asPo() {
1633 setAsProfileOwner(admin1);
1634
Makoto Onuki068c54a2015-10-13 14:34:03 -07001635 DpmTestUtils.assertRestrictions(
1636 DpmTestUtils.newRestrictions(),
1637 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1638 .ensureUserRestrictions()
1639 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001640
1641 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1643 eq(DpmMockContext.CALLER_USER_HANDLE),
1644 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001645 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 reset(mContext.userManagerInternal);
1647
Makoto Onukia4f11972015-10-01 13:19:58 -07001648 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1650 eq(DpmMockContext.CALLER_USER_HANDLE),
1651 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1652 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001653 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001655
Makoto Onuki068c54a2015-10-13 14:34:03 -07001656 DpmTestUtils.assertRestrictions(
1657 DpmTestUtils.newRestrictions(
1658 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1659 UserManager.DISALLOW_OUTGOING_CALLS
1660 ),
1661 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1662 .ensureUserRestrictions()
1663 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001664 DpmTestUtils.assertRestrictions(
1665 DpmTestUtils.newRestrictions(
1666 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1667 UserManager.DISALLOW_OUTGOING_CALLS
1668 ),
1669 dpm.getUserRestrictions(admin1)
1670 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001671
1672 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1674 eq(DpmMockContext.CALLER_USER_HANDLE),
1675 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001676 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001677 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001678
1679 DpmTestUtils.assertRestrictions(
1680 DpmTestUtils.newRestrictions(
1681 UserManager.DISALLOW_OUTGOING_CALLS
1682 ),
1683 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1684 .ensureUserRestrictions()
1685 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001686 DpmTestUtils.assertRestrictions(
1687 DpmTestUtils.newRestrictions(
1688 UserManager.DISALLOW_OUTGOING_CALLS
1689 ),
1690 dpm.getUserRestrictions(admin1)
1691 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001692
1693 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1695 eq(DpmMockContext.CALLER_USER_HANDLE),
1696 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001697 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001699
Makoto Onuki068c54a2015-10-13 14:34:03 -07001700 DpmTestUtils.assertRestrictions(
1701 DpmTestUtils.newRestrictions(),
1702 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1703 .ensureUserRestrictions()
1704 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001705 DpmTestUtils.assertRestrictions(
1706 DpmTestUtils.newRestrictions(),
1707 dpm.getUserRestrictions(admin1)
1708 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001709
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1711 // though when DO sets them they'll be applied globally.
1712 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1713 reset(mContext.userManagerInternal);
1714 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1715 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1716 eq(DpmMockContext.CALLER_USER_HANDLE),
1717 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1718 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001719 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 reset(mContext.userManagerInternal);
1721
1722 dpm.setCameraDisabled(admin1, true);
1723 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1724 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001725 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001727 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 reset(mContext.userManagerInternal);
1729
Makoto Onukia4f11972015-10-01 13:19:58 -07001730 // TODO Make sure restrictions are written to the file.
1731 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001732
Esteban Talavera548a04b2016-12-20 15:22:30 +00001733
1734 public void testDefaultEnabledUserRestrictions() throws Exception {
1735 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1736 mContext.callerPermissions.add(permission.MANAGE_USERS);
1737 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1738 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1739
1740 // First, set DO.
1741
1742 // Call from a process on the system user.
1743 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1744
1745 // Make sure admin1 is installed on system user.
1746 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1747
1748 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1749 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1750 UserHandle.USER_SYSTEM));
1751
1752 // Check that the user restrictions that are enabled by default are set. Then unset them.
1753 String[] defaultRestrictions = UserRestrictionsUtils
1754 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1755 assertTrue(defaultRestrictions.length > 0);
1756 DpmTestUtils.assertRestrictions(
1757 DpmTestUtils.newRestrictions(defaultRestrictions),
1758 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1759 );
1760 DpmTestUtils.assertRestrictions(
1761 DpmTestUtils.newRestrictions(defaultRestrictions),
1762 dpm.getUserRestrictions(admin1)
1763 );
1764 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1765 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001766 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001767 eq(true) /* isDeviceOwner */,
1768 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001769 );
1770 reset(mContext.userManagerInternal);
1771
1772 for (String restriction : defaultRestrictions) {
1773 dpm.clearUserRestriction(admin1, restriction);
1774 }
1775
1776 assertNoDeviceOwnerRestrictions();
1777
1778 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1779 reset(mContext.userManagerInternal);
1780 initializeDpms();
1781 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1782 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1783
1784 assertNoDeviceOwnerRestrictions();
1785
1786 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1787 // is set as it wasn't enabled during setDeviceOwner.
1788 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1789 assertFalse(UserRestrictionsUtils
1790 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1791 UserRestrictionsUtils
1792 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1793 try {
1794 reset(mContext.userManagerInternal);
1795 initializeDpms();
1796 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1797 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1798
1799 DpmTestUtils.assertRestrictions(
1800 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1801 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1802 );
1803 DpmTestUtils.assertRestrictions(
1804 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1805 dpm.getUserRestrictions(admin1)
1806 );
1807 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1808 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001809 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001810 eq(true) /* isDeviceOwner */,
1811 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001812 );
1813 reset(mContext.userManagerInternal);
1814
1815 // Remove the restriction.
1816 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1817
1818 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1819 initializeDpms();
1820 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1821 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1822 assertNoDeviceOwnerRestrictions();
1823 } finally {
1824 UserRestrictionsUtils
1825 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1826 }
1827 }
1828
1829 private void assertNoDeviceOwnerRestrictions() {
1830 DpmTestUtils.assertRestrictions(
1831 DpmTestUtils.newRestrictions(),
1832 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1833 );
1834 DpmTestUtils.assertRestrictions(
1835 DpmTestUtils.newRestrictions(),
1836 dpm.getUserRestrictions(admin1)
1837 );
1838 }
1839
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001840 public void testGetMacAddress() throws Exception {
1841 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1842 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1843 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1844
1845 // In this test, change the caller user to "system".
1846 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1847
1848 // Make sure admin1 is installed on system user.
1849 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1850
1851 // Test 1. Caller doesn't have DO or DA.
1852 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001853 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001854 fail();
1855 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001856 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001857 }
1858
1859 // DO needs to be an DA.
1860 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1861 assertTrue(dpm.isAdminActive(admin1));
1862
1863 // Test 2. Caller has DA, but not DO.
1864 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001865 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001866 fail();
1867 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001868 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001869 }
1870
1871 // Test 3. Caller has PO, but not DO.
1872 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1873 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001874 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001875 fail();
1876 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001877 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001878 }
1879
1880 // Remove PO.
1881 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001882 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001883 // Test 4, Caller is DO now.
1884 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1885
1886 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001887 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001888
1889 // 4-2. Returns WifiInfo, but with the default MAC.
1890 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001891 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001892
1893 // 4-3. With a real MAC address.
1894 final WifiInfo wi = new WifiInfo();
1895 wi.setMacAddress("11:22:33:44:55:66");
1896 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001897 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001898 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001899
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001900 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001901 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1902 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1903
1904 // In this test, change the caller user to "system".
1905 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1906
1907 // Make sure admin1 is installed on system user.
1908 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1909
1910 // Set admin1 as DA.
1911 dpm.setActiveAdmin(admin1, false);
1912 assertTrue(dpm.isAdminActive(admin1));
1913 try {
1914 dpm.reboot(admin1);
1915 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1916 } catch (SecurityException expected) {
1917 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1918 }
1919
1920 // Set admin1 as PO.
1921 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1922 try {
1923 dpm.reboot(admin1);
1924 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1925 } catch (SecurityException expected) {
1926 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1927 }
1928
1929 // Remove PO and add DO.
1930 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001931 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001932 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1933
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001934 // admin1 is DO.
1935 // Set current call state of device to ringing.
1936 when(mContext.telephonyManager.getCallState())
1937 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1938 try {
1939 dpm.reboot(admin1);
1940 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1941 } catch (IllegalStateException expected) {
1942 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1943 }
1944
1945 // Set current call state of device to dialing/active.
1946 when(mContext.telephonyManager.getCallState())
1947 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1948 try {
1949 dpm.reboot(admin1);
1950 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1951 } catch (IllegalStateException expected) {
1952 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1953 }
1954
1955 // Set current call state of device to idle.
1956 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001957 dpm.reboot(admin1);
1958 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001959
1960 public void testSetGetSupportText() {
1961 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1962 dpm.setActiveAdmin(admin1, true);
1963 dpm.setActiveAdmin(admin2, true);
1964 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1965
1966 // Null default support messages.
1967 {
1968 assertNull(dpm.getLongSupportMessage(admin1));
1969 assertNull(dpm.getShortSupportMessage(admin1));
1970 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1971 assertNull(dpm.getShortSupportMessageForUser(admin1,
1972 DpmMockContext.CALLER_USER_HANDLE));
1973 assertNull(dpm.getLongSupportMessageForUser(admin1,
1974 DpmMockContext.CALLER_USER_HANDLE));
1975 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1976 }
1977
1978 // Only system can call the per user versions.
1979 {
1980 try {
1981 dpm.getShortSupportMessageForUser(admin1,
1982 DpmMockContext.CALLER_USER_HANDLE);
1983 fail("Only system should be able to call getXXXForUser versions");
1984 } catch (SecurityException expected) {
1985 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1986 }
1987 try {
1988 dpm.getLongSupportMessageForUser(admin1,
1989 DpmMockContext.CALLER_USER_HANDLE);
1990 fail("Only system should be able to call getXXXForUser versions");
1991 } catch (SecurityException expected) {
1992 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1993 }
1994 }
1995
1996 // Can't set message for admin in another uid.
1997 {
1998 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1999 try {
2000 dpm.setShortSupportMessage(admin1, "Some text");
2001 fail("Admins should only be able to change their own support text.");
2002 } catch (SecurityException expected) {
2003 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
2004 }
2005 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2006 }
2007
2008 // Set/Get short returns what it sets and other admins text isn't changed.
2009 {
2010 final String supportText = "Some text to test with.";
2011 dpm.setShortSupportMessage(admin1, supportText);
2012 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2013 assertNull(dpm.getLongSupportMessage(admin1));
2014 assertNull(dpm.getShortSupportMessage(admin2));
2015
2016 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2017 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2018 DpmMockContext.CALLER_USER_HANDLE));
2019 assertNull(dpm.getShortSupportMessageForUser(admin2,
2020 DpmMockContext.CALLER_USER_HANDLE));
2021 assertNull(dpm.getLongSupportMessageForUser(admin1,
2022 DpmMockContext.CALLER_USER_HANDLE));
2023 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2024
2025 dpm.setShortSupportMessage(admin1, null);
2026 assertNull(dpm.getShortSupportMessage(admin1));
2027 }
2028
2029 // Set/Get long returns what it sets and other admins text isn't changed.
2030 {
2031 final String supportText = "Some text to test with.\nWith more text.";
2032 dpm.setLongSupportMessage(admin1, supportText);
2033 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2034 assertNull(dpm.getShortSupportMessage(admin1));
2035 assertNull(dpm.getLongSupportMessage(admin2));
2036
2037 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2038 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2039 DpmMockContext.CALLER_USER_HANDLE));
2040 assertNull(dpm.getLongSupportMessageForUser(admin2,
2041 DpmMockContext.CALLER_USER_HANDLE));
2042 assertNull(dpm.getShortSupportMessageForUser(admin1,
2043 DpmMockContext.CALLER_USER_HANDLE));
2044 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2045
2046 dpm.setLongSupportMessage(admin1, null);
2047 assertNull(dpm.getLongSupportMessage(admin1));
2048 }
2049 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002050
phweiss73145f42017-01-17 19:06:38 +01002051 public void testCreateAdminSupportIntent() throws Exception {
2052 // Setup device owner.
2053 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2054 setupDeviceOwner();
2055
2056 // Nonexisting permission returns null
2057 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2058 assertNull(intent);
2059
2060 // Existing permission that is not set returns null
2061 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2062 assertNull(intent);
2063
2064 // Existing permission that is not set by device/profile owner returns null
2065 when(mContext.userManager.hasUserRestriction(
2066 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2067 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2068 .thenReturn(true);
2069 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2070 assertNull(intent);
2071
2072 // Permission that is set by device owner returns correct intent
2073 when(mContext.userManager.getUserRestrictionSource(
2074 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2075 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2076 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2077 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2078 assertNotNull(intent);
2079 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2080 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2081 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2082 assertEquals(admin1,
2083 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2084 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2085 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2086
2087 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2088 // user restrictions
2089
2090 // Camera is not disabled
2091 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2092 assertNull(intent);
2093
2094 // Camera is disabled
2095 dpm.setCameraDisabled(admin1, true);
2096 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2097 assertNotNull(intent);
2098 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2099 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2100
2101 // Screen capture is not disabled
2102 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2103 assertNull(intent);
2104
2105 // Screen capture is disabled
2106 dpm.setScreenCaptureDisabled(admin1, true);
2107 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2108 assertNotNull(intent);
2109 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2110 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2111
2112 // Same checks for different user
2113 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2114 // Camera should be disabled by device owner
2115 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2116 assertNotNull(intent);
2117 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2118 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2119 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2120 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2121 // ScreenCapture should not be disabled by device owner
2122 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2123 assertNull(intent);
2124 }
2125
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002126 /**
2127 * Test for:
2128 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002129 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002130 * {@link DevicePolicyManager#isAffiliatedUser}
2131 */
2132 public void testUserAffiliation() throws Exception {
2133 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2134 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2135 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2136
2137 // Check that the system user is unaffiliated.
2138 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2139 assertFalse(dpm.isAffiliatedUser());
2140
2141 // Set a device owner on the system user. Check that the system user becomes affiliated.
2142 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2143 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2144 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2145 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002146 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002147
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002148 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002149 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2150 setAsProfileOwner(admin2);
2151 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002152 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002153
2154 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2155 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002156 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002157 userAffiliationIds.add("red");
2158 userAffiliationIds.add("green");
2159 userAffiliationIds.add("blue");
2160 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002161 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002162 assertFalse(dpm.isAffiliatedUser());
2163
2164 // Have the device owner specify a set of affiliation ids that do not intersect with those
2165 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002166 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002167 deviceAffiliationIds.add("cyan");
2168 deviceAffiliationIds.add("yellow");
2169 deviceAffiliationIds.add("magenta");
2170 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2171 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002172 MoreAsserts.assertContentsInAnyOrder(
2173 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002174 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2175 assertFalse(dpm.isAffiliatedUser());
2176
2177 // Have the profile owner specify a set of affiliation ids that intersect with those
2178 // specified by the device owner. Check that the test user becomes affiliated.
2179 userAffiliationIds.add("yellow");
2180 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002181 MoreAsserts.assertContentsInAnyOrder(
2182 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002183 assertTrue(dpm.isAffiliatedUser());
2184
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002185 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2186 dpm.setAffiliationIds(admin2, Collections.emptyList());
2187 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002188 assertFalse(dpm.isAffiliatedUser());
2189
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002190 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2191 dpm.setAffiliationIds(admin2, userAffiliationIds);
2192 assertTrue(dpm.isAffiliatedUser());
2193 dpm.clearProfileOwner(admin2);
2194 assertFalse(dpm.isAffiliatedUser());
2195
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002196 // Check that the system user remains affiliated.
2197 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2198 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002199
2200 // Clear the device owner - the user becomes unaffiliated.
2201 clearDeviceOwner();
2202 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002203 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002204
2205 public void testGetUserProvisioningState_defaultResult() {
2206 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2207 }
2208
2209 public void testSetUserProvisioningState_permission() throws Exception {
2210 setupProfileOwner();
2211 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2212
2213 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2214 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2215 }
2216
2217 public void testSetUserProvisioningState_unprivileged() throws Exception {
2218 setupProfileOwner();
2219 try {
2220 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2221 DpmMockContext.CALLER_USER_HANDLE);
2222 fail("Expected SecurityException");
2223 } catch (SecurityException expected) {
2224 }
2225 }
2226
2227 public void testSetUserProvisioningState_noManagement() {
2228 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2229 try {
2230 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2231 DpmMockContext.CALLER_USER_HANDLE);
2232 fail("IllegalStateException expected");
2233 } catch (IllegalStateException e) {
2234 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2235 e.getMessage());
2236 }
2237 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2238 }
2239
2240 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2241 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2242 setupDeviceOwner();
2243 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2244
2245 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2246 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2247 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2248 }
2249
2250 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2251 throws Exception {
2252 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2253 setupDeviceOwner();
2254 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2255
2256 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2257 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2258 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2259 }
2260
2261 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2262 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2263 setupDeviceOwner();
2264 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2265
2266 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2267 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2268 }
2269
2270 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2271 throws Exception {
2272 setupProfileOwner();
2273 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2274
2275 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2276 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2277 DevicePolicyManager.STATE_USER_UNMANAGED);
2278 }
2279
2280 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2281 throws Exception {
2282 setupProfileOwner();
2283 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2284
2285 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2286 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2287 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2288 }
2289
2290 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2291 setupProfileOwner();
2292 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2293
2294 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2295 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2296 }
2297
2298 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2299 setupProfileOwner();
2300 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2301
2302 try {
2303 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2304 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2305 DevicePolicyManager.STATE_USER_UNMANAGED);
2306 fail("Expected IllegalStateException");
2307 } catch (IllegalStateException e) {
2308 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2309 e.getMessage());
2310 }
2311 }
2312
2313 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2314 throws Exception {
2315 setupProfileOwner();
2316 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2317
2318 try {
2319 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2320 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2321 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2322 fail("Expected IllegalStateException");
2323 } catch (IllegalStateException e) {
2324 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2325 e.getMessage());
2326 }
2327 }
2328
2329 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2330 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2331 for (int state : states) {
2332 dpm.setUserProvisioningState(state, userId);
2333 assertEquals(state, dpm.getUserProvisioningState());
2334 }
2335 }
2336
2337 private void setupProfileOwner() throws Exception {
2338 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2339
2340 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2341 dpm.setActiveAdmin(admin1, false);
2342 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2343
2344 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2345 }
2346
2347 private void setupDeviceOwner() throws Exception {
2348 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2349
2350 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2351 dpm.setActiveAdmin(admin1, false);
2352 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2353
2354 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2355 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002356
2357 public void testSetMaximumTimeToLock() {
2358 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2359
2360 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2361 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2362
2363 reset(mMockContext.powerManagerInternal);
2364 reset(mMockContext.settings);
2365
2366 dpm.setMaximumTimeToLock(admin1, 0);
2367 verifyScreenTimeoutCall(null, false);
2368 reset(mMockContext.powerManagerInternal);
2369 reset(mMockContext.settings);
2370
2371 dpm.setMaximumTimeToLock(admin1, 1);
2372 verifyScreenTimeoutCall(1, true);
2373 reset(mMockContext.powerManagerInternal);
2374 reset(mMockContext.settings);
2375
2376 dpm.setMaximumTimeToLock(admin2, 10);
2377 verifyScreenTimeoutCall(null, false);
2378 reset(mMockContext.powerManagerInternal);
2379 reset(mMockContext.settings);
2380
2381 dpm.setMaximumTimeToLock(admin1, 5);
2382 verifyScreenTimeoutCall(5, true);
2383 reset(mMockContext.powerManagerInternal);
2384 reset(mMockContext.settings);
2385
2386 dpm.setMaximumTimeToLock(admin2, 4);
2387 verifyScreenTimeoutCall(4, true);
2388 reset(mMockContext.powerManagerInternal);
2389 reset(mMockContext.settings);
2390
2391 dpm.setMaximumTimeToLock(admin1, 0);
2392 reset(mMockContext.powerManagerInternal);
2393 reset(mMockContext.settings);
2394
2395 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2396 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2397 reset(mMockContext.powerManagerInternal);
2398 reset(mMockContext.settings);
2399
2400 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2401 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2402 reset(mMockContext.powerManagerInternal);
2403 reset(mMockContext.settings);
2404
2405 dpm.setMaximumTimeToLock(admin2, 10);
2406 verifyScreenTimeoutCall(10, true);
2407 reset(mMockContext.powerManagerInternal);
2408 reset(mMockContext.settings);
2409
2410 // There's no restriction; shold be set to MAX.
2411 dpm.setMaximumTimeToLock(admin2, 0);
2412 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2413 }
2414
Michal Karpinski943aabd2016-10-06 11:09:25 +01002415 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2416 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2417 setupDeviceOwner();
2418 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2419
Michal Karpinskid084ca52017-01-18 15:54:18 +00002420 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2421 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2422 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2423 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2424 - ONE_MINUTE;
2425
2426 // verify that the minimum timeout cannot be modified on user builds (system property is
2427 // not being read)
2428 mContext.buildMock.isDebuggable = false;
2429
2430 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2431 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2432 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2433
2434 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2435
2436 // restore to the debuggable build state
2437 mContext.buildMock.isDebuggable = true;
2438
2439 // Always return the default (second arg) when getting system property for long type
2440 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2441 new Answer<Long>() {
2442 @Override
2443 public Long answer(InvocationOnMock invocation) throws Throwable {
2444 return (Long) invocation.getArguments()[1];
2445 }
2446 }
2447 );
2448
2449 // reset to default (0 means the admin is not participating, so default should be returned)
2450 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002451
2452 // aggregation should be the default if unset by any admin
2453 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2454 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2455
2456 // admin not participating by default
2457 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2458
2459 //clamping from the top
2460 dpm.setRequiredStrongAuthTimeout(admin1,
2461 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2462 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2463 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2464 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2465 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2466
Michal Karpinskid084ca52017-01-18 15:54:18 +00002467 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002468 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2469 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2470 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2471 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2472
2473 // clamping from the bottom
2474 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2475 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2476 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2477
Michal Karpinskid084ca52017-01-18 15:54:18 +00002478 // values within range
2479 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2480 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2481 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2482
2483 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2484 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2485 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002486
2487 // reset to default
2488 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2489 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2490 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2491 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2492
2493 // negative value
2494 try {
2495 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2496 fail("Didn't throw IllegalArgumentException");
2497 } catch (IllegalArgumentException iae) {
2498 }
2499 }
2500
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002501 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2502 boolean shouldStayOnWhilePluggedInBeCleared) {
2503 if (expectedTimeout == null) {
2504 verify(mMockContext.powerManagerInternal, times(0))
2505 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2506 } else {
2507 verify(mMockContext.powerManagerInternal, times(1))
2508 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2509 }
2510 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2511 // UnfinishedVerificationException.
2512 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002513
Esteban Talavera01576862016-12-15 11:16:44 +00002514 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002515 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2516 .thenReturn(false);
2517 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2518 .thenReturn(false);
2519 initializeDpms();
2520 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2521 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2522 .thenReturn(true);
2523 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2524
2525 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002526 }
Victor Chang3e794af2016-03-04 13:48:17 +00002527
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002528 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2529 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002530 mContext.packageName = admin1.getPackageName();
2531 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002532 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2533 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2534 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2535 false);
2536 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2537 }
2538
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002539 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2540 setup_DeviceAdminFeatureOff();
2541 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2542 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2543 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2544 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2545 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2546 assertCheckProvisioningPreCondition(
2547 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2548 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2549 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2550 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2551 }
2552
Esteban Talavera01576862016-12-15 11:16:44 +00002553 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002554 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2555 .thenReturn(false);
2556 initializeDpms();
2557 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2558 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2559 .thenReturn(true);
2560 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2561
2562 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002563 }
Victor Chang3e794af2016-03-04 13:48:17 +00002564
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002565 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2566 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002567 mContext.packageName = admin1.getPackageName();
2568 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002569 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2570 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2571 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2572 false);
2573 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2574
2575 // Test again when split user is on
2576 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2577 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2578 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2579 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2580 true);
2581 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2582 }
2583
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002584 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2585 setup_ManagedProfileFeatureOff();
2586 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2587 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2588 DevicePolicyManager.CODE_OK);
2589 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2590 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2591 assertCheckProvisioningPreCondition(
2592 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2593 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2594 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2595 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2596
2597 // Test again when split user is on
2598 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2599 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2600 DevicePolicyManager.CODE_OK);
2601 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2602 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2603 assertCheckProvisioningPreCondition(
2604 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2605 DevicePolicyManager.CODE_OK);
2606 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2607 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2608 }
2609
Esteban Talavera01576862016-12-15 11:16:44 +00002610 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002611 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2612 .thenReturn(true);
2613 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2614 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2615 .thenReturn(true);
2616 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2617
2618 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002619 }
Victor Chang3e794af2016-03-04 13:48:17 +00002620
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002621 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2622 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002623 mContext.packageName = admin1.getPackageName();
2624 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002625 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2626 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2627 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2628 false /* because of non-split user */);
2629 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2630 false /* because of non-split user */);
2631 }
2632
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002633 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002634 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002635 setup_nonSplitUser_firstBoot_primaryUser();
2636 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2637 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2638 DevicePolicyManager.CODE_OK);
2639 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2640 DevicePolicyManager.CODE_OK);
2641 assertCheckProvisioningPreCondition(
2642 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2643 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2644 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2645 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2646 }
2647
Esteban Talavera01576862016-12-15 11:16:44 +00002648 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002649 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2650 .thenReturn(true);
2651 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2652 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2653 .thenReturn(true);
2654 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2655
2656 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002657 }
Victor Chang3e794af2016-03-04 13:48:17 +00002658
Nicolas Prevot45d29072017-01-18 16:11:19 +00002659 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2660 setDeviceOwner();
2661 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2662 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2663 }
2664
2665 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2666 setup_nonSplitUser_withDo_primaryUser();
2667 final int MANAGED_PROFILE_USER_ID = 18;
2668 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2669 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2670 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2671 false /* we can't remove a managed profile */)).thenReturn(false);
2672 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2673 true)).thenReturn(true);
2674 }
2675
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002676 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2677 throws Exception {
2678 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002679 mContext.packageName = admin1.getPackageName();
2680 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002681 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2682 false/* because of completed device setup */);
2683 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2684 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2685 false/* because of non-split user */);
2686 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2687 false/* because of non-split user */);
2688 }
2689
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002690 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2691 throws Exception {
2692 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2693 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2694 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2695 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2696 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2697 DevicePolicyManager.CODE_OK);
2698 assertCheckProvisioningPreCondition(
2699 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2700 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2701 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2702 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2703 }
2704
Nicolas Prevot45d29072017-01-18 16:11:19 +00002705 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2706 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002707 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002708 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2709
2710 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2711 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002712 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002713
2714 // COMP mode is allowed.
2715 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2716 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002717 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002718
Nicolas Prevot45d29072017-01-18 16:11:19 +00002719 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002720 assertCheckProvisioningPreCondition(
2721 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002722 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002723 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002724 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2725 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2726 }
Esteban Talavera01576862016-12-15 11:16:44 +00002727
Nicolas Prevot45d29072017-01-18 16:11:19 +00002728 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2729 setup_nonSplitUser_withDo_primaryUser();
2730 mContext.packageName = admin1.getPackageName();
2731 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2732 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2733 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002734 when(mContext.userManager.hasUserRestriction(
2735 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2736 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2737 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002738 when(mContext.userManager.getUserRestrictionSource(
2739 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2740 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2741 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2742 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2743 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002745 assertCheckProvisioningPreCondition(
2746 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002747 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002748 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002749 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2750 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2751 }
Esteban Talavera01576862016-12-15 11:16:44 +00002752
Nicolas Prevot45d29072017-01-18 16:11:19 +00002753 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2754 throws Exception {
2755 setup_nonSplitUser_withDo_primaryUser();
2756 mContext.packageName = admin1.getPackageName();
2757 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002758 // The DO should not be allowed to initiate provisioning if the restriction is set by
2759 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002760 when(mContext.userManager.hasUserRestriction(
2761 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2762 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2763 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002764 when(mContext.userManager.getUserRestrictionSource(
2765 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2766 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2767 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2768 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2769 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002770 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2771
2772 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002773 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002774 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002775 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2777 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2778 }
2779
2780 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2781 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2782 mContext.packageName = admin1.getPackageName();
2783 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2784
2785 // We can delete the managed profile to create a new one, so provisioning is allowed.
2786 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2787 DevicePolicyManager.CODE_OK);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2789 assertCheckProvisioningPreCondition(
2790 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2791 DpmMockContext.ANOTHER_PACKAGE_NAME,
2792 DevicePolicyManager.CODE_OK);
2793 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2794 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2795 }
2796
2797 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2798 throws Exception {
2799 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2800 mContext.packageName = admin1.getPackageName();
2801 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2802 when(mContext.userManager.hasUserRestriction(
2803 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2804 eq(UserHandle.SYSTEM)))
2805 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002806 when(mContext.userManager.getUserRestrictionSource(
2807 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2808 eq(UserHandle.SYSTEM)))
2809 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002810
2811 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002812 assertCheckProvisioningPreCondition(
2813 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2814 DpmMockContext.ANOTHER_PACKAGE_NAME,
2815 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2816 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2817 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002818
2819 // But the device owner can still do it because it has set the restriction itself.
2820 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2821 DevicePolicyManager.CODE_OK);
2822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002823 }
2824
2825 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002826 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2827 .thenReturn(true);
2828 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2829 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2830 .thenReturn(false);
2831 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2832
2833 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002834 }
Victor Chang3e794af2016-03-04 13:48:17 +00002835
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002836 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2837 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002838 mContext.packageName = admin1.getPackageName();
2839 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2842 false /* because canAddMoreManagedProfiles returns false */);
2843 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2844 true);
2845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2846 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002847 }
2848
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002849 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2850 throws Exception {
2851 setup_splitUser_firstBoot_systemUser();
2852 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2853 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2854 DevicePolicyManager.CODE_OK);
2855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002856 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002857 assertCheckProvisioningPreCondition(
2858 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2859 DevicePolicyManager.CODE_OK);
2860 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2861 DevicePolicyManager.CODE_SYSTEM_USER);
2862 }
2863
Esteban Talavera01576862016-12-15 11:16:44 +00002864 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002865 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2866 .thenReturn(true);
2867 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2868 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2869 .thenReturn(false);
2870 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2871
2872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002873 }
Victor Chang3e794af2016-03-04 13:48:17 +00002874
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002875 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2876 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002877 mContext.packageName = admin1.getPackageName();
2878 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002879 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2880 true/* it's undefined behavior. Can be changed into false in the future */);
2881 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2882 false /* because canAddMoreManagedProfiles returns false */);
2883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2884 true/* it's undefined behavior. Can be changed into false in the future */);
2885 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2886 false/* because calling uid is system user */);
2887 }
2888
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002889 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2890 throws Exception {
2891 setup_splitUser_afterDeviceSetup_systemUser();
2892 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2893 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2894 DevicePolicyManager.CODE_OK);
2895 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002896 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002897 assertCheckProvisioningPreCondition(
2898 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2899 DevicePolicyManager.CODE_OK);
2900 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2901 DevicePolicyManager.CODE_SYSTEM_USER);
2902 }
2903
Esteban Talavera01576862016-12-15 11:16:44 +00002904 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002905 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2906 .thenReturn(true);
2907 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2908 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2909 true)).thenReturn(true);
2910 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2911
2912 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002913 }
Victor Chang3e794af2016-03-04 13:48:17 +00002914
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002915 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2916 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002917 mContext.packageName = admin1.getPackageName();
2918 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2922 true);
2923 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002924 }
2925
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002926 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002927 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002928 setup_splitUser_firstBoot_primaryUser();
2929 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2930 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2931 DevicePolicyManager.CODE_OK);
2932 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2933 DevicePolicyManager.CODE_OK);
2934 assertCheckProvisioningPreCondition(
2935 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2936 DevicePolicyManager.CODE_OK);
2937 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2938 DevicePolicyManager.CODE_OK);
2939 }
2940
Esteban Talavera01576862016-12-15 11:16:44 +00002941 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002942 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2943 .thenReturn(true);
2944 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2945 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2946 true)).thenReturn(true);
2947 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2948
2949 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002950 }
Victor Chang3e794af2016-03-04 13:48:17 +00002951
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002952 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2953 throws Exception {
2954 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002955 mContext.packageName = admin1.getPackageName();
2956 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002957 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2958 true/* it's undefined behavior. Can be changed into false in the future */);
2959 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2960 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2961 true/* it's undefined behavior. Can be changed into false in the future */);
2962 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2963 false/* because user setup completed */);
2964 }
2965
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002966 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002967 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002968 setup_splitUser_afterDeviceSetup_primaryUser();
2969 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2970 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2971 DevicePolicyManager.CODE_OK);
2972 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2973 DevicePolicyManager.CODE_OK);
2974 assertCheckProvisioningPreCondition(
2975 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2976 DevicePolicyManager.CODE_OK);
2977 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2978 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2979 }
2980
Esteban Talavera01576862016-12-15 11:16:44 +00002981 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002982 setDeviceOwner();
2983
2984 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2985 .thenReturn(true);
2986 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2987 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2988 .thenReturn(false);
2989 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2990
2991 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002992 }
Victor Chang3e794af2016-03-04 13:48:17 +00002993
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002994 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2995 throws Exception {
2996 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002997 mContext.packageName = admin1.getPackageName();
2998 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3000 false /* can't provision managed profile on system user */);
3001 }
3002
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003003 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003004 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003005 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3006 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3007 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3008 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3009 }
3010
3011 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003012 setDeviceOwner();
3013
3014 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3015 .thenReturn(true);
3016 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3017 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3018 true)).thenReturn(true);
3019 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3020
3021 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003022 }
Victor Chang3e794af2016-03-04 13:48:17 +00003023
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003024 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3025 throws Exception {
3026 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003027 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3028 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3030 }
3031
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003032 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003033 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003034 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3035 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003036
3037 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003038 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3039 DevicePolicyManager.CODE_OK);
3040 }
3041
3042 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003043 setDeviceOwner();
3044
3045 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3046 .thenReturn(true);
3047 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003048 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003049 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3050 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003051 .thenReturn(true);
3052 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003053 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003054 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3055 true)).thenReturn(true);
3056 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3057
3058 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003059 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003060
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003061 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3062 throws Exception {
3063 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003064 mContext.packageName = admin1.getPackageName();
3065 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3067 }
3068
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003069 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3070 throws Exception {
3071 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3072 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3073 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3074 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3075 }
3076
3077 public void testCheckProvisioningPreCondition_permission() {
3078 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3079 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003080 dpm.checkProvisioningPreCondition(
3081 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003082 fail("Didn't throw SecurityException");
3083 } catch (SecurityException expected) {
3084 }
3085 }
3086
Victor Chang3577ed22016-08-25 18:49:26 +01003087 public void testForceUpdateUserSetupComplete_permission() {
3088 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3089 try {
3090 dpm.forceUpdateUserSetupComplete();
3091 fail("Didn't throw SecurityException");
3092 } catch (SecurityException expected) {
3093 }
3094 }
3095
3096 public void testForceUpdateUserSetupComplete_systemUser() {
3097 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3098 // GIVEN calling from user 20
3099 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3100 try {
3101 dpm.forceUpdateUserSetupComplete();
3102 fail("Didn't throw SecurityException");
3103 } catch (SecurityException expected) {
3104 }
3105 }
3106
3107 public void testForceUpdateUserSetupComplete_userbuild() {
3108 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3109 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3110
3111 final int userId = UserHandle.USER_SYSTEM;
3112 // GIVEN userComplete is false in SettingsProvider
3113 setUserSetupCompleteForUser(false, userId);
3114
3115 // GIVEN userComplete is true in DPM
3116 DevicePolicyManagerService.DevicePolicyData userData =
3117 new DevicePolicyManagerService.DevicePolicyData(userId);
3118 userData.mUserSetupComplete = true;
3119 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3120
3121 // GIVEN it's user build
3122 mContext.buildMock.isDebuggable = false;
3123
3124 assertTrue(dpms.hasUserSetupCompleted());
3125
3126 dpm.forceUpdateUserSetupComplete();
3127
3128 // THEN the state in dpms is not changed
3129 assertTrue(dpms.hasUserSetupCompleted());
3130 }
3131
3132 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3133 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3134 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3135
3136 final int userId = UserHandle.USER_SYSTEM;
3137 // GIVEN userComplete is false in SettingsProvider
3138 setUserSetupCompleteForUser(false, userId);
3139
3140 // GIVEN userComplete is true in DPM
3141 DevicePolicyManagerService.DevicePolicyData userData =
3142 new DevicePolicyManagerService.DevicePolicyData(userId);
3143 userData.mUserSetupComplete = true;
3144 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3145
3146 // GIVEN it's userdebug build
3147 mContext.buildMock.isDebuggable = true;
3148
3149 assertTrue(dpms.hasUserSetupCompleted());
3150
3151 dpm.forceUpdateUserSetupComplete();
3152
3153 // THEN the state in dpms is not changed
3154 assertFalse(dpms.hasUserSetupCompleted());
3155 }
3156
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003157 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003158 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003159 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3160 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3161 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3162 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003163 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003164 }
3165
3166 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3167 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3168 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003169
3170 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3171 // feature is disabled because there are non-affiliated secondary users.
3172 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003173 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3174 .thenReturn(true);
3175
3176 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003177 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003178
3179 // Enabling logging should not change the timestamp.
3180 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003181 verify(mContext.settings)
3182 .securityLogSetLoggingEnabledProperty(true);
3183 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3184 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003185 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003186
3187 // Retrieving the logs should update the timestamp.
3188 final long beforeRetrieval = System.currentTimeMillis();
3189 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003190 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003191 final long afterRetrieval = System.currentTimeMillis();
3192 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3193 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3194
3195 // Retrieving the pre-boot logs should update the timestamp.
3196 Thread.sleep(2);
3197 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003198 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003199 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3200
3201 // Checking the timestamp again should not change it.
3202 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003203 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003204
3205 // Retrieving the logs again should update the timestamp.
3206 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003207 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003208 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3209
3210 // Disabling logging should not change the timestamp.
3211 Thread.sleep(2);
3212 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003213 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003214
3215 // Restarting the DPMS should not lose the timestamp.
3216 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003217 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003218
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003219 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3220 mContext.binder.callingUid = 1234567;
3221 mContext.callerPermissions.add(permission.MANAGE_USERS);
3222 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3223 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3224
3225 // System can retrieve the timestamp.
3226 mContext.binder.clearCallingIdentity();
3227 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3228
3229 // Removing the device owner should clear the timestamp.
3230 clearDeviceOwner();
3231 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003232 }
3233
3234 public void testGetLastBugReportRequestTime() throws Exception {
3235 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3236 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003237
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003238 mContext.packageName = admin1.getPackageName();
3239 mContext.applicationInfo = new ApplicationInfo();
3240 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3241 .thenReturn(Color.WHITE);
3242 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3243 anyObject())).thenReturn(Color.WHITE);
3244
Esteban Talaverad36dd152016-12-15 08:51:45 +00003245 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3246 // feature is disabled because there are non-affiliated secondary users.
3247 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3248
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003249 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003250 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003251
3252 // Requesting a bug report should update the timestamp.
3253 final long beforeRequest = System.currentTimeMillis();
3254 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003255 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003256 final long afterRequest = System.currentTimeMillis();
3257 assertTrue(bugReportRequestTime >= beforeRequest);
3258 assertTrue(bugReportRequestTime <= afterRequest);
3259
3260 // Checking the timestamp again should not change it.
3261 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003262 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003263
3264 // Restarting the DPMS should not lose the timestamp.
3265 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003266 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003267
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003268 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3269 mContext.binder.callingUid = 1234567;
3270 mContext.callerPermissions.add(permission.MANAGE_USERS);
3271 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3272 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3273
3274 // System can retrieve the timestamp.
3275 mContext.binder.clearCallingIdentity();
3276 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3277
3278 // Removing the device owner should clear the timestamp.
3279 clearDeviceOwner();
3280 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003281 }
3282
3283 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3284 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3285 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003286 mContext.packageName = admin1.getPackageName();
3287 mContext.applicationInfo = new ApplicationInfo();
3288 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3289 .thenReturn(Color.WHITE);
3290 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3291 anyObject())).thenReturn(Color.WHITE);
3292
3293 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3294 // feature is disabled because there are non-affiliated secondary users.
3295 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003296 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3297 .thenReturn(true);
3298
3299 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003300 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003301
3302 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3303 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003304 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003305
3306 // Enabling logging should not change the timestamp.
3307 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003308 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003309
3310 // Retrieving the logs should update the timestamp.
3311 final long beforeRetrieval = System.currentTimeMillis();
3312 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003313 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003314 final long afterRetrieval = System.currentTimeMillis();
3315 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3316 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3317
3318 // Checking the timestamp again should not change it.
3319 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003320 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003321
3322 // Retrieving the logs again should update the timestamp.
3323 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003324 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003325 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3326
3327 // Disabling logging should not change the timestamp.
3328 Thread.sleep(2);
3329 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003330 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003331
3332 // Restarting the DPMS should not lose the timestamp.
3333 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003334 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3335
3336 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3337 mContext.binder.callingUid = 1234567;
3338 mContext.callerPermissions.add(permission.MANAGE_USERS);
3339 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3340 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3341
3342 // System can retrieve the timestamp.
3343 mContext.binder.clearCallingIdentity();
3344 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3345
3346 // Removing the device owner should clear the timestamp.
3347 clearDeviceOwner();
3348 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003349 }
3350
Tony Mak2f26b792016-11-28 17:54:51 +00003351 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3352 // Setup device owner.
3353 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3354 setupDeviceOwner();
3355
3356 // Only device owner is setup, the result list should be empty.
3357 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3358 MoreAsserts.assertEmpty(targetUsers);
3359
3360 // Setup a managed profile managed by the same admin.
3361 final int MANAGED_PROFILE_USER_ID = 15;
3362 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3363 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3364
3365 // Add a secondary user, it should never talk with.
3366 final int ANOTHER_USER_ID = 36;
3367 mContext.addUser(ANOTHER_USER_ID, 0);
3368
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003369 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3370 // other.
3371 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3372 MoreAsserts.assertEmpty(targetUsers);
3373
3374 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3375 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3376 MoreAsserts.assertEmpty(targetUsers);
3377
3378 // Setting affiliation ids
3379 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3380 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3381 dpm.setAffiliationIds(admin1, userAffiliationIds);
3382
3383 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3384 dpm.setAffiliationIds(admin1, userAffiliationIds);
3385
Tony Mak2f26b792016-11-28 17:54:51 +00003386 // Calling from device owner admin, the result list should just contain the managed
3387 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003388 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003389 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3390 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3391
3392 // Calling from managed profile admin, the result list should just contain the system
3393 // user id.
3394 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3395 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3396 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003397
3398 // Changing affiliation ids in one
3399 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3400
3401 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3402 // to each other.
3403 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3404 MoreAsserts.assertEmpty(targetUsers);
3405
3406 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3407 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3408 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003409 }
3410
3411 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3412 // Setup a device owner.
3413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3414 setupDeviceOwner();
3415
3416 // Set up a managed profile managed by different package.
3417 final int MANAGED_PROFILE_USER_ID = 15;
3418 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3419 final ComponentName adminDifferentPackage =
3420 new ComponentName("another.package", "whatever.class");
3421 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3422
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003423 // Setting affiliation ids
3424 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3425 dpm.setAffiliationIds(admin1, userAffiliationIds);
3426
3427 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3428 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3429
Tony Mak2f26b792016-11-28 17:54:51 +00003430 // Calling from device owner admin, we should get zero bind device admin target users as
3431 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003432 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003433 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3434 MoreAsserts.assertEmpty(targetUsers);
3435
3436 // Calling from managed profile admin, we should still get zero target users for the same
3437 // reason.
3438 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3439 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3440 MoreAsserts.assertEmpty(targetUsers);
3441 }
3442
Esteban Talaverabdcada92017-02-01 14:20:06 +00003443 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3444 // Setup a device owner.
3445 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3446 setupDeviceOwner();
3447 // Lock task packages are updated when loading user data.
3448 verify(mContext.iactivityManager)
3449 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3450
3451 // Set up a managed profile managed by different package (package name shouldn't matter)
3452 final int MANAGED_PROFILE_USER_ID = 15;
3453 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3454 final ComponentName adminDifferentPackage =
3455 new ComponentName("another.package", "whatever.class");
3456 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3457 verify(mContext.iactivityManager)
3458 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3459
3460 // The DO can still set lock task packages
3461 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3462 final String[] doPackages = {"doPackage1", "doPackage2"};
3463 dpm.setLockTaskPackages(admin1, doPackages);
3464 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3465 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3466 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3467 verify(mContext.iactivityManager)
3468 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3469
3470 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3471 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3472 final String[] poPackages = {"poPackage1", "poPackage2"};
3473 try {
3474 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3475 fail("Didn't throw expected security exception.");
3476 } catch (SecurityException expected) {
3477 }
3478 try {
3479 dpm.getLockTaskPackages(adminDifferentPackage);
3480 fail("Didn't throw expected security exception.");
3481 } catch (SecurityException expected) {
3482 }
3483 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3484
3485 // Setting same affiliation ids
3486 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3487 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3488 dpm.setAffiliationIds(admin1, userAffiliationIds);
3489
3490 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3491 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3492
3493 // Now the managed profile can set lock task packages.
3494 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3495 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3496 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3497 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3498 verify(mContext.iactivityManager)
3499 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3500
3501 // Unaffiliate the profile, lock task mode no longer available on the profile.
3502 dpm.setAffiliationIds(adminDifferentPackage, Collections.<String>emptyList());
3503 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3504 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3505 verify(mContext.iactivityManager, times(2))
3506 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3507
3508 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3509 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3510 }
3511
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003512 public void testIsDeviceManaged() throws Exception {
3513 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3514 setupDeviceOwner();
3515
3516 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3517 // find out that the device has a device owner.
3518 assertTrue(dpm.isDeviceManaged());
3519 mContext.binder.callingUid = 1234567;
3520 mContext.callerPermissions.add(permission.MANAGE_USERS);
3521 assertTrue(dpm.isDeviceManaged());
3522 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3523 mContext.binder.clearCallingIdentity();
3524 assertTrue(dpm.isDeviceManaged());
3525
3526 clearDeviceOwner();
3527
3528 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3529 // not have a device owner.
3530 mContext.binder.callingUid = 1234567;
3531 mContext.callerPermissions.add(permission.MANAGE_USERS);
3532 assertFalse(dpm.isDeviceManaged());
3533 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3534 mContext.binder.clearCallingIdentity();
3535 assertFalse(dpm.isDeviceManaged());
3536 }
3537
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003538 public void testDeviceOwnerOrganizationName() throws Exception {
3539 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3540 setupDeviceOwner();
3541
3542 dpm.setOrganizationName(admin1, "organization");
3543
3544 // Device owner can retrieve organization managing the device.
3545 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3546
3547 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3548 mContext.binder.callingUid = 1234567;
3549 mContext.callerPermissions.add(permission.MANAGE_USERS);
3550 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3551 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3552
3553 // System can retrieve organization managing the device.
3554 mContext.binder.clearCallingIdentity();
3555 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3556
3557 // Removing the device owner clears the organization managing the device.
3558 clearDeviceOwner();
3559 assertNull(dpm.getDeviceOwnerOrganizationName());
3560 }
3561
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003562 public void testWipeDataManagedProfile() throws Exception {
3563 final int MANAGED_PROFILE_USER_ID = 15;
3564 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3565 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3566 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3567
3568 // Even if the caller is the managed profile, the current user is the user 0
3569 when(mContext.iactivityManager.getCurrentUser())
3570 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3571
3572 dpm.wipeData(0);
3573 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3574 MANAGED_PROFILE_USER_ID);
3575 }
3576
3577 public void testWipeDataManagedProfileDisallowed() throws Exception {
3578 final int MANAGED_PROFILE_USER_ID = 15;
3579 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3580 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3581
3582 // Even if the caller is the managed profile, the current user is the user 0
3583 when(mContext.iactivityManager.getCurrentUser())
3584 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3585
3586 when(mContext.userManager.getUserRestrictionSource(
3587 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3588 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3589 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3590 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3591 try {
3592 // The PO is not allowed to remove the profile if the user restriction was set on the
3593 // profile by the system
3594 dpm.wipeData(0);
3595 fail("SecurityException not thrown");
3596 } catch (SecurityException expected) {
3597 }
3598 }
3599
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003600 public void testWipeDataDeviceOwner() throws Exception {
3601 setDeviceOwner();
3602 when(mContext.userManager.getUserRestrictionSource(
3603 UserManager.DISALLOW_FACTORY_RESET,
3604 UserHandle.SYSTEM))
3605 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3606
3607 dpm.wipeData(0);
3608 verify(mContext.recoverySystem).rebootWipeUserData(
3609 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3610 }
3611
3612 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3613 setDeviceOwner();
3614 when(mContext.userManager.getUserRestrictionSource(
3615 UserManager.DISALLOW_FACTORY_RESET,
3616 UserHandle.SYSTEM))
3617 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3618 try {
3619 // The DO is not allowed to wipe the device if the user restriction was set
3620 // by the system
3621 dpm.wipeData(0);
3622 fail("SecurityException not thrown");
3623 } catch (SecurityException expected) {
3624 }
3625 }
3626
3627 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3628 final int MANAGED_PROFILE_USER_ID = 15;
3629 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3630 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3631
3632 // Even if the caller is the managed profile, the current user is the user 0
3633 when(mContext.iactivityManager.getCurrentUser())
3634 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3635
3636 when(mContext.userManager.getUserRestrictionSource(
3637 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3638 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3639 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3640
3641 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3642 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3643
3644 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3645 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3646 // Failed password attempts on the parent user are taken into account, as there isn't a
3647 // separate work challenge.
3648 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3649 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3650 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3651
3652 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3653 // both the user restriction and the policy were set by the PO.
3654 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3655 MANAGED_PROFILE_USER_ID);
3656 verifyZeroInteractions(mContext.recoverySystem);
3657 }
3658
3659 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3660 throws Exception {
3661 final int MANAGED_PROFILE_USER_ID = 15;
3662 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3663 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3664
3665 // Even if the caller is the managed profile, the current user is the user 0
3666 when(mContext.iactivityManager.getCurrentUser())
3667 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3668
3669 when(mContext.userManager.getUserRestrictionSource(
3670 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3671 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3672 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3673
3674 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3675 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3676
3677 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3678 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3679 // Failed password attempts on the parent user are taken into account, as there isn't a
3680 // separate work challenge.
3681 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3682 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3683 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3684
3685 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3686 // not wiped.
3687 verify(mContext.userManagerInternal, never())
3688 .removeUserEvenWhenDisallowed(anyInt());
3689 verifyZeroInteractions(mContext.recoverySystem);
3690 }
3691
3692 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3693 setDeviceOwner();
3694 when(mContext.userManager.getUserRestrictionSource(
3695 UserManager.DISALLOW_FACTORY_RESET,
3696 UserHandle.SYSTEM))
3697 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3698
3699 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3700
3701 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3702 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3703 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3704 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3705 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3706
3707 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3708 // user restriction and the policy were set by the DO.
3709 verify(mContext.recoverySystem).rebootWipeUserData(
3710 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3711 }
3712
3713 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3714 setDeviceOwner();
3715 when(mContext.userManager.getUserRestrictionSource(
3716 UserManager.DISALLOW_FACTORY_RESET,
3717 UserHandle.SYSTEM))
3718 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3719
3720 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3721
3722 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3723 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3724 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3725 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3726 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3727
3728 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3729 verifyZeroInteractions(mContext.recoverySystem);
3730 verify(mContext.userManagerInternal, never())
3731 .removeUserEvenWhenDisallowed(anyInt());
3732 }
3733
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003734 public void testGetPermissionGrantState() throws Exception {
3735 final String permission = "some.permission";
3736 final String app1 = "com.example.app1";
3737 final String app2 = "com.example.app2";
3738
3739 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3740 .thenReturn(PackageManager.PERMISSION_GRANTED);
3741 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3742 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3743 when(mContext.packageManager.getPermissionFlags(permission, app1,
3744 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3745 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3746 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3747 .thenReturn(PackageManager.PERMISSION_DENIED);
3748 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3749 UserHandle.SYSTEM);
3750 when(mContext.packageManager.getPermissionFlags(permission, app2,
3751 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3752
3753 // System can retrieve permission grant state.
3754 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003755 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003756 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3757 dpm.getPermissionGrantState(null, app1, permission));
3758 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3759 dpm.getPermissionGrantState(null, app2, permission));
3760
3761 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003762 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3763 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003764 try {
3765 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003766 fail("Didn't throw SecurityException");
3767 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003768 }
3769
3770 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003771 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3772 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003773 setAsProfileOwner(admin1);
3774 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3775 dpm.getPermissionGrantState(admin1, app1, permission));
3776 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3777 dpm.getPermissionGrantState(admin1, app2, permission));
3778 }
3779
Rubin Xuaab7a412016-12-30 21:13:29 +00003780 public void testResetPasswordWithToken() throws Exception {
3781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3782 setupDeviceOwner();
3783 // test token validation
3784 try {
3785 dpm.setResetPasswordToken(admin1, new byte[31]);
3786 fail("should not have accepted tokens too short");
3787 } catch (IllegalArgumentException expected) {
3788 }
3789 // test adding a token
3790 final byte[] token = new byte[32];
3791 final long handle = 123456;
3792 final String password = "password";
3793 when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3794 .thenReturn(handle);
3795 assertTrue(dpm.setResetPasswordToken(admin1, token));
3796
3797 // test password activation
3798 when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3799 .thenReturn(true);
3800 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3801
3802 // test reset password with token
3803 when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3804 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3805 eq(UserHandle.USER_SYSTEM)))
3806 .thenReturn(true);
3807 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3808
3809 // test removing a token
3810 when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3811 .thenReturn(true);
3812 assertTrue(dpm.clearResetPasswordToken(admin1));
3813 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003814
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003815 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3816 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3817 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3818 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3819 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3820 DpmMockContext.SYSTEM_UID);
3821 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3822 DpmMockContext.SYSTEM_UID);
3823
3824 // Set up a device owner.
3825 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003826 setupDeviceOwner();
3827
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003828 // First and second user set IMEs manually.
3829 mContext.binder.callingUid = firstUserSystemUid;
3830 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3831 mContext.binder.callingUid = secondUserSystemUid;
3832 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003833
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003834 // Device owner changes IME for first user.
3835 mContext.binder.callingUid = deviceOwnerUid;
3836 when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003837 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003838 dpm.setSecureSetting(admin1, currentIme, "ime2");
3839 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003840 UserHandle.USER_SYSTEM);
3841 reset(mContext.settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003842 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3843 mContext.binder.callingUid = firstUserSystemUid;
3844 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3845 mContext.binder.callingUid = secondUserSystemUid;
3846 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003847
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003848 // Second user changes IME manually.
3849 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3850 mContext.binder.callingUid = firstUserSystemUid;
3851 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3852 mContext.binder.callingUid = secondUserSystemUid;
3853 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003854
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003855 // First user changes IME manually.
3856 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3857 mContext.binder.callingUid = firstUserSystemUid;
3858 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3859 mContext.binder.callingUid = secondUserSystemUid;
3860 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003861
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003862 // Device owner changes IME for first user again.
3863 mContext.binder.callingUid = deviceOwnerUid;
3864 when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003865 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003866 dpm.setSecureSetting(admin1, currentIme, "ime3");
3867 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003868 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003869 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3870 mContext.binder.callingUid = firstUserSystemUid;
3871 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3872 mContext.binder.callingUid = secondUserSystemUid;
3873 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003874
3875 // Restarting the DPMS should not lose information.
3876 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003877 mContext.binder.callingUid = firstUserSystemUid;
3878 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3879 mContext.binder.callingUid = secondUserSystemUid;
3880 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003881
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003882 // Device owner can find out whether it set the current IME itself.
3883 mContext.binder.callingUid = deviceOwnerUid;
3884 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003885
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003886 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003887 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003888 mContext.binder.callingUid = firstUserSystemUid;
3889 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3890 mContext.binder.callingUid = secondUserSystemUid;
3891 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003892 }
3893
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003894 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3895 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3896 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3897 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3898 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3899 DpmMockContext.SYSTEM_UID);
3900 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3901 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003902
3903 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003904 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003905 setupProfileOwner();
3906
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003907 // First and second user set IMEs manually.
3908 mContext.binder.callingUid = firstUserSystemUid;
3909 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3910 mContext.binder.callingUid = secondUserSystemUid;
3911 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003912
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003913 // Profile owner changes IME for second user.
3914 mContext.binder.callingUid = profileOwnerUid;
3915 when(mContext.settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003916 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003917 dpm.setSecureSetting(admin1, currentIme, "ime2");
3918 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003919 DpmMockContext.CALLER_USER_HANDLE);
3920 reset(mContext.settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003921 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3922 mContext.binder.callingUid = firstUserSystemUid;
3923 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3924 mContext.binder.callingUid = secondUserSystemUid;
3925 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003926
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003927 // First user changes IME manually.
3928 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3929 mContext.binder.callingUid = firstUserSystemUid;
3930 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3931 mContext.binder.callingUid = secondUserSystemUid;
3932 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003933
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003934 // Second user changes IME manually.
3935 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3936 mContext.binder.callingUid = firstUserSystemUid;
3937 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3938 mContext.binder.callingUid = secondUserSystemUid;
3939 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003940
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003941 // Profile owner changes IME for second user again.
3942 mContext.binder.callingUid = profileOwnerUid;
3943 when(mContext.settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003944 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003945 dpm.setSecureSetting(admin1, currentIme, "ime3");
3946 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003947 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003948 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3949 mContext.binder.callingUid = firstUserSystemUid;
3950 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3951 mContext.binder.callingUid = secondUserSystemUid;
3952 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003953
3954 // Restarting the DPMS should not lose information.
3955 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003956 mContext.binder.callingUid = firstUserSystemUid;
3957 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3958 mContext.binder.callingUid = secondUserSystemUid;
3959 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003960
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003961 // Profile owner can find out whether it set the current IME itself.
3962 mContext.binder.callingUid = profileOwnerUid;
3963 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003964
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003965 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003966 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003967 mContext.binder.callingUid = firstUserSystemUid;
3968 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3969 mContext.binder.callingUid = secondUserSystemUid;
3970 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003971 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003972
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003973 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00003974 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003975 setDeviceOwner();
3976
Robin Lee2c68dad2017-03-17 12:50:24 +00003977 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
3978 caller.packageName = admin1.getPackageName();
3979 caller.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3980
3981 verifyCanGetOwnerInstalledCaCerts(admin1, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003982 }
3983
3984 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00003985 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003986 setAsProfileOwner(admin1);
3987
Robin Lee2c68dad2017-03-17 12:50:24 +00003988 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
3989 caller.packageName = admin1.getPackageName();
3990 caller.binder.callingUid = DpmMockContext.CALLER_UID;
3991
3992 verifyCanGetOwnerInstalledCaCerts(admin1, caller);
3993 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003994 }
3995
3996 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00003997 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003998 setAsProfileOwner(admin1);
3999
4000 final String delegate = "com.example.delegate";
4001 final int delegateUid = setupPackageInPackageManager(delegate, 20988);
4002 dpm.setCertInstallerPackage(admin1, delegate);
4003
Robin Lee2c68dad2017-03-17 12:50:24 +00004004 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
4005 caller.packageName = delegate;
4006 caller.binder.callingUid = delegateUid;
4007
4008 verifyCanGetOwnerInstalledCaCerts(null, caller);
4009 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004010 }
4011
Robin Lee2c68dad2017-03-17 12:50:24 +00004012 private void verifyCanGetOwnerInstalledCaCerts(
4013 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004014 final String alias = "cert";
4015 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004016
4017 // device admin (used for posting the tls notification)
4018 final DpmMockContext admin1Context;
4019 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4020 admin1Context = callerContext;
4021 } else {
4022 admin1Context = new DpmMockContext(mRealTestContext, "test-admin");
4023 admin1Context.packageName = admin1.getPackageName();
4024 admin1Context.applicationInfo = new ApplicationInfo();
4025 }
4026 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4027
4028 // caller: device admin or delegated certificate installer
4029 callerContext.applicationInfo = new ApplicationInfo();
4030 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4031
4032 // system_server
4033 final DpmMockContext serviceContext = mContext;
4034 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4035 serviceContext.addPackageContext(callerUser, admin1Context);
4036 serviceContext.addPackageContext(callerUser, callerContext);
4037
4038 // Install a CA cert.
4039 runAsCaller(callerContext, dpms, (dpm) -> {
4040 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4041 .thenReturn(alias);
4042 assertTrue(dpm.installCaCert(caller, caCert));
4043 when(mContext.keyChainConnection.getService().getUserCaAliases())
4044 .thenReturn(asSlice(new String[] {alias}));
4045
4046 });
4047
4048 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4049 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004050 flushTasks();
4051
Robin Lee2c68dad2017-03-17 12:50:24 +00004052 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4053
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004054 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004055 runAsCaller(admin1Context, dpms, (dpm) -> {
4056 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4057 assertEquals(Arrays.asList(alias), installedCaCerts);
4058 ownerInstalledCaCerts.addAll(installedCaCerts);
4059 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004060
4061 // Restarting the DPMS should not lose information.
4062 initializeDpms();
Robin Lee2c68dad2017-03-17 12:50:24 +00004063 runAsCaller(admin1Context, dpms, (dpm) -> {
4064 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
4065 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004066
4067 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004068 runAsCaller(serviceContext, dpms, (dpm) -> {
4069 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004070
Robin Lee2c68dad2017-03-17 12:50:24 +00004071 // Remove the CA cert.
4072 reset(mContext.keyChainConnection.getService());
4073 });
4074
4075 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4076 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004077 flushTasks();
4078
4079 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4080 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004081 runAsCaller(admin1Context, dpms, (dpm) -> {
4082 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4083 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004084 }
4085
Robin Lee2c68dad2017-03-17 12:50:24 +00004086 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4087 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004088 final String alias = "cert";
4089 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004090
4091 // device admin (used for posting the tls notification)
4092 final DpmMockContext admin1Context;
4093 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4094 admin1Context = callerContext;
4095 } else {
4096 admin1Context = new DpmMockContext(mRealTestContext, "test-admin");
4097 admin1Context.packageName = admin1.getPackageName();
4098 admin1Context.applicationInfo = new ApplicationInfo();
4099 }
4100 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4101
4102 // caller: device admin or delegated certificate installer
4103 callerContext.applicationInfo = new ApplicationInfo();
4104 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4105
4106 // system_server
4107 final DpmMockContext serviceContext = mContext;
4108 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4109 serviceContext.addPackageContext(callerUser, admin1Context);
4110 serviceContext.addPackageContext(callerUser, callerContext);
4111
4112 // Install a CA cert as caller
4113 runAsCaller(callerContext, dpms, (dpm) -> {
4114 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4115 .thenReturn(alias);
4116 assertTrue(dpm.installCaCert(callerName, caCert));
4117 });
4118
4119 // Fake the CA cert as having been installed
4120 when(serviceContext.keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004121 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004122 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4123 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004124 flushTasks();
4125
Robin Lee2c68dad2017-03-17 12:50:24 +00004126 // Removing the Profile Owner should clear the information on which CA certs were installed
4127 runAsCaller(admin1Context, dpms, (dpm) -> {
4128 dpm.clearProfileOwner(admin1);
4129 });
4130
4131 runAsCaller(serviceContext, dpms, (dpm) -> {
4132 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4133 assertNotNull(ownerInstalledCaCerts);
4134 assertTrue(ownerInstalledCaCerts.isEmpty());
4135 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004136 }
4137
Victor Chang3e794af2016-03-04 13:48:17 +00004138 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
4139 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
4140 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4141 dpms.notifyChangeToContentObserver(
4142 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4143 }
4144
4145 private void assertProvisioningAllowed(String action, boolean expected) {
4146 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4147 dpm.isProvisioningAllowed(action));
4148 }
Tony Mak2f26b792016-11-28 17:54:51 +00004149
Nicolas Prevot45d29072017-01-18 16:11:19 +00004150 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4151 int uid) {
4152 String previousPackageName = mContext.packageName;
4153 int previousUid = mMockContext.binder.callingUid;
4154
4155 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4156 mContext.packageName = packageName;
4157 mMockContext.binder.callingUid = uid;
4158 assertProvisioningAllowed(action, expected);
4159
4160 // Set the previous package name / calling uid to go back to the initial state.
4161 mContext.packageName = previousPackageName;
4162 mMockContext.binder.callingUid = previousUid;
4163 }
4164
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004165 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004166 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4167 }
4168
4169 private void assertCheckProvisioningPreCondition(
4170 String action, String packageName, int provisioningCondition) {
4171 assertEquals("checkProvisioningPreCondition("
4172 + action + ", " + packageName + ") returning unexpected result",
4173 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004174 }
4175
Tony Mak2f26b792016-11-28 17:54:51 +00004176 /**
4177 * Setup a managed profile with the specified admin and its uid.
4178 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4179 * @param adminUid uid of the admin package.
4180 * @param copyFromAdmin package information for {@code admin} will be built based on this
4181 * component's information.
4182 */
4183 private void addManagedProfile(
4184 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4185 final int userId = UserHandle.getUserId(adminUid);
4186 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
4187 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4188 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4189 dpm.setActiveAdmin(admin, false, userId);
4190 assertTrue(dpm.setProfileOwner(admin, null, userId));
4191 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4192 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004193
4194 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004195 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004196 */
Robin Leeabaa0692017-02-20 20:54:22 +00004197 private static StringParceledListSlice asSlice(String[] s) {
4198 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004199 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004200
4201 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004202 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4203 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004204
Robin Lee2c68dad2017-03-17 12:50:24 +00004205 // We can't let exceptions happen on the background thread. Throw them here if they happen
4206 // so they still cause the test to fail despite being suppressed.
4207 mContext.rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004208 }
Victor Chang3e794af2016-03-04 13:48:17 +00004209}