DevicePolicyManagerTest.java revision 192bb0bc54f6bb418f5778fe26eb2e68514290fb
1/*
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 */
16package com.android.server.devicepolicy;
17
18import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
19import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
20import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
21
22import android.Manifest.permission;
23import android.app.Activity;
24import android.app.Notification;
25import android.app.NotificationManager;
26import android.app.admin.DeviceAdminReceiver;
27import android.app.admin.DevicePolicyManager;
28import android.app.admin.DevicePolicyManagerInternal;
29import android.content.BroadcastReceiver;
30import android.content.ComponentName;
31import android.content.Context;
32import android.content.Intent;
33import android.content.ServiceConnection;
34import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageInfo;
36import android.content.pm.PackageManager;
37import android.content.pm.StringParceledListSlice;
38import android.content.res.Resources;
39import android.graphics.Color;
40import android.net.IIpConnectivityMetrics;
41import android.net.Uri;
42import android.content.pm.UserInfo;
43import android.net.wifi.WifiInfo;
44import android.os.Build.VERSION_CODES;
45import android.os.Bundle;
46import android.os.IBinder;
47import android.os.Process;
48import android.os.UserHandle;
49import android.os.UserManager;
50import android.os.UserManagerInternal;
51import android.provider.Settings;
52import android.security.IKeyChainService;
53import android.security.KeyChain;
54import android.telephony.TelephonyManager;
55import android.test.MoreAsserts;
56import android.test.suitebuilder.annotation.SmallTest;
57import android.util.ArraySet;
58import android.util.Pair;
59
60import com.android.internal.R;
61import com.android.internal.widget.LockPatternUtils;
62import com.android.server.LocalServices;
63import com.android.server.SystemService;
64import com.android.server.pm.UserRestrictionsUtils;
65
66import org.hamcrest.BaseMatcher;
67import org.hamcrest.Description;
68import org.mockito.invocation.InvocationOnMock;
69import org.mockito.stubbing.Answer;
70
71import java.util.ArrayList;
72import java.util.Arrays;
73import java.util.Collections;
74import java.util.HashMap;
75import java.util.List;
76import java.util.Map;
77import java.util.Set;
78import java.util.concurrent.TimeUnit;
79
80import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
81import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
82
83import static org.mockito.Matchers.any;
84import static org.mockito.Matchers.anyInt;
85import static org.mockito.Matchers.anyLong;
86import static org.mockito.Matchers.anyObject;
87import static org.mockito.Matchers.anyString;
88import static org.mockito.Matchers.eq;
89import static org.mockito.Matchers.isNull;
90import static org.mockito.Mockito.atLeast;
91import static org.mockito.Mockito.doAnswer;
92import static org.mockito.Mockito.doReturn;
93import static org.mockito.Mockito.mock;
94import static org.mockito.Mockito.never;
95import static org.mockito.Mockito.reset;
96import static org.mockito.Mockito.timeout;
97import static org.mockito.Mockito.times;
98import static org.mockito.Mockito.verify;
99import static org.mockito.Mockito.verifyZeroInteractions;
100import static org.mockito.Mockito.when;
101import static org.mockito.hamcrest.MockitoHamcrest.argThat;
102
103/**
104 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
105 * You can run them via:
106 m FrameworksServicesTests &&
107 adb install \
108   -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
109 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
110   -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
111
112 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
113 *
114 * , or:
115 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
116 */
117@SmallTest
118public class DevicePolicyManagerTest extends DpmTestBase {
119    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
123    private DpmMockContext mContext;
124    public DevicePolicyManager dpm;
125    public DevicePolicyManagerServiceTestable dpms;
126
127    /*
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
155    @Override
156    protected void setUp() throws Exception {
157        super.setUp();
158
159        mContext = getContext();
160
161        when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
162                .thenReturn(true);
163
164        // By default, pretend all users are running and unlocked.
165        when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
166
167        initializeDpms();
168
169        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
170        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
171        setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
172        setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
173
174        setUpUserManager();
175    }
176
177    private void initializeDpms() {
178        // Need clearCallingIdentity() to pass permission checks.
179        final long ident = mContext.binder.clearCallingIdentity();
180        try {
181            LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
182
183            dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
184
185            dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
186            dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
187
188            dpm = new DevicePolicyManagerTestable(mContext, dpms);
189        } finally {
190            mContext.binder.restoreCallingIdentity(ident);
191        }
192    }
193
194    private void setUpUserManager() {
195        // Emulate UserManager.set/getApplicationRestriction().
196        final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
197
198        // UM.setApplicationRestrictions() will save to appRestrictions.
199        doAnswer(new Answer<Void>() {
200            @Override
201            public Void answer(InvocationOnMock invocation) throws Throwable {
202                String pkg = (String) invocation.getArguments()[0];
203                Bundle bundle = (Bundle) invocation.getArguments()[1];
204                UserHandle user = (UserHandle) invocation.getArguments()[2];
205
206                appRestrictions.put(Pair.create(pkg, user), bundle);
207
208                return null;
209            }
210        }).when(mContext.userManager).setApplicationRestrictions(
211                anyString(), any(Bundle.class), any(UserHandle.class));
212
213        // UM.getApplicationRestrictions() will read from appRestrictions.
214        doAnswer(new Answer<Bundle>() {
215            @Override
216            public Bundle answer(InvocationOnMock invocation) throws Throwable {
217                String pkg = (String) invocation.getArguments()[0];
218                UserHandle user = (UserHandle) invocation.getArguments()[1];
219
220                return appRestrictions.get(Pair.create(pkg, user));
221            }
222        }).when(mContext.userManager).getApplicationRestrictions(
223                anyString(), any(UserHandle.class));
224
225        // Add the first secondary user.
226        mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
227    }
228
229    private void setAsProfileOwner(ComponentName admin) {
230        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
231        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
232
233        // PO needs to be an DA.
234        dpm.setActiveAdmin(admin, /* replace =*/ false);
235
236        // Fire!
237        assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
238
239        // Check
240        assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
241    }
242
243    public void testHasNoFeature() throws Exception {
244        when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
245                .thenReturn(false);
246
247        LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
248        new DevicePolicyManagerServiceTestable(mContext, dataDir);
249
250        // If the device has no DPMS feature, it shouldn't register the local service.
251        assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
252    }
253
254    /**
255     * Caller doesn't have proper permissions.
256     */
257    public void testSetActiveAdmin_SecurityException() {
258        // 1. Failure cases.
259
260        // Caller doesn't have MANAGE_DEVICE_ADMINS.
261        try {
262            dpm.setActiveAdmin(admin1, false);
263            fail("Didn't throw SecurityException");
264        } catch (SecurityException expected) {
265        }
266
267        // Caller has MANAGE_DEVICE_ADMINS, but for different user.
268        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
269        try {
270            dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
271            fail("Didn't throw SecurityException");
272        } catch (SecurityException expected) {
273        }
274    }
275
276    /**
277     * Test for:
278     * {@link DevicePolicyManager#setActiveAdmin}
279     * with replace=false and replace=true
280     * {@link DevicePolicyManager#isAdminActive}
281     * {@link DevicePolicyManager#isAdminActiveAsUser}
282     * {@link DevicePolicyManager#getActiveAdmins}
283     * {@link DevicePolicyManager#getActiveAdminsAsUser}
284     */
285    public void testSetActiveAdmin() throws Exception {
286        // 1. Make sure the caller has proper permissions.
287        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
288
289        // 2. Call the API.
290        dpm.setActiveAdmin(admin1, /* replace =*/ false);
291
292        // 3. Verify internal calls.
293
294        // Check if the boradcast is sent.
295        verify(mContext.spiedContext).sendBroadcastAsUser(
296                MockUtils.checkIntentAction(
297                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
298                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
299        verify(mContext.spiedContext).sendBroadcastAsUser(
300                MockUtils.checkIntentAction(
301                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
302                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
303
304        verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
305                eq(admin1.getPackageName()),
306                eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
307                eq(PackageManager.DONT_KILL_APP),
308                eq(DpmMockContext.CALLER_USER_HANDLE),
309                anyString());
310
311        // TODO Verify other calls too.
312
313        // Make sure it's active admin1.
314        assertTrue(dpm.isAdminActive(admin1));
315        assertFalse(dpm.isAdminActive(admin2));
316        assertFalse(dpm.isAdminActive(admin3));
317
318        // But not admin1 for a different user.
319
320        // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
321        // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
322        mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
323
324        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
325        assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
326
327        mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
328
329        // Next, add one more admin.
330        // Before doing so, update the application info, now it's enabled.
331        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
332                PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
333
334        dpm.setActiveAdmin(admin2, /* replace =*/ false);
335
336        // Now we have two admins.
337        assertTrue(dpm.isAdminActive(admin1));
338        assertTrue(dpm.isAdminActive(admin2));
339        assertFalse(dpm.isAdminActive(admin3));
340
341        // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
342        // again.  (times(1) because it was previously called for admin1)
343        verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
344                eq(admin1.getPackageName()),
345                eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
346                eq(PackageManager.DONT_KILL_APP),
347                eq(DpmMockContext.CALLER_USER_HANDLE),
348                anyString());
349
350        // 4. Add the same admin1 again without replace, which should throw.
351        try {
352            dpm.setActiveAdmin(admin1, /* replace =*/ false);
353            fail("Didn't throw");
354        } catch (IllegalArgumentException expected) {
355        }
356
357        // 5. Add the same admin1 again with replace, which should succeed.
358        dpm.setActiveAdmin(admin1, /* replace =*/ true);
359
360        // TODO make sure it's replaced.
361
362        // 6. Test getActiveAdmins()
363        List<ComponentName> admins = dpm.getActiveAdmins();
364        assertEquals(2, admins.size());
365        assertEquals(admin1, admins.get(0));
366        assertEquals(admin2, admins.get(1));
367
368        // Another user has no admins.
369        mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
370
371        assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
372                dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
373
374        mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
375    }
376
377    public void testSetActiveAdmin_multiUsers() throws Exception {
378
379        final int ANOTHER_USER_ID = 100;
380        final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
381
382        mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
383
384        // Set up pacakge manager for the other user.
385        setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
386
387        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
388
389        dpm.setActiveAdmin(admin1, /* replace =*/ false);
390
391        mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
392        dpm.setActiveAdmin(admin2, /* replace =*/ false);
393
394
395        mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
396        assertTrue(dpm.isAdminActive(admin1));
397        assertFalse(dpm.isAdminActive(admin2));
398
399        mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
400        assertFalse(dpm.isAdminActive(admin1));
401        assertTrue(dpm.isAdminActive(admin2));
402    }
403
404    /**
405     * Test for:
406     * {@link DevicePolicyManager#setActiveAdmin}
407     * with replace=false
408     */
409    public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
410        // 1. Make sure the caller has proper permissions.
411        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
412
413        dpm.setActiveAdmin(admin1, /* replace =*/ false);
414        assertTrue(dpm.isAdminActive(admin1));
415
416        // Add the same admin1 again without replace, which should throw.
417        try {
418            dpm.setActiveAdmin(admin1, /* replace =*/ false);
419            fail("Didn't throw");
420        } catch (IllegalArgumentException expected) {
421        }
422    }
423
424    /**
425     * Test for:
426     * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
427     * BIND_DEVICE_ADMIN.
428     */
429    public void testSetActiveAdmin_permissionCheck() throws Exception {
430        // 1. Make sure the caller has proper permissions.
431        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
432
433        try {
434            dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
435            fail();
436        } catch (IllegalArgumentException expected) {
437            assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
438        }
439        assertFalse(dpm.isAdminActive(adminNoPerm));
440
441        // Change the target API level to MNC.  Now it can be set as DA.
442        setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
443                VERSION_CODES.M);
444        dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
445        assertTrue(dpm.isAdminActive(adminNoPerm));
446
447        // TODO Test the "load from the file" case where DA will still be loaded even without
448        // BIND_DEVICE_ADMIN and target API is N.
449    }
450
451    /**
452     * Test for:
453     * {@link DevicePolicyManager#removeActiveAdmin}
454     */
455    public void testRemoveActiveAdmin_SecurityException() {
456        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
457
458        // Add admin.
459
460        dpm.setActiveAdmin(admin1, /* replace =*/ false);
461
462        assertTrue(dpm.isAdminActive(admin1));
463
464        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
465
466        // Directly call the DPMS method with a different userid, which should fail.
467        try {
468            dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
469            fail("Didn't throw SecurityException");
470        } catch (SecurityException expected) {
471        }
472
473        // Try to remove active admin with a different caller userid should fail too, without
474        // having MANAGE_DEVICE_ADMINS.
475        mContext.callerPermissions.clear();
476
477        // Change the caller, and call into DPMS directly with a different user-id.
478
479        mContext.binder.callingUid = 1234567;
480        try {
481            dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
482            fail("Didn't throw SecurityException");
483        } catch (SecurityException expected) {
484        }
485    }
486
487    /**
488     * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
489     * (because we can't send the remove broadcast).
490     */
491    public void testRemoveActiveAdmin_userNotRunningOrLocked() {
492        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
493
494        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
495
496        // Add admin.
497
498        dpm.setActiveAdmin(admin1, /* replace =*/ false);
499
500        assertTrue(dpm.isAdminActive(admin1));
501
502        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
503
504        // 1. User not unlocked.
505        when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
506                .thenReturn(false);
507        try {
508            dpm.removeActiveAdmin(admin1);
509            fail("Didn't throw IllegalStateException");
510        } catch (IllegalStateException expected) {
511            MoreAsserts.assertContainsRegex(
512                    "User must be running and unlocked", expected.getMessage());
513        }
514
515        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
516
517        // 2. User unlocked.
518        when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
519                .thenReturn(true);
520
521        dpm.removeActiveAdmin(admin1);
522        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
523    }
524
525    /**
526     * Test for:
527     * {@link DevicePolicyManager#removeActiveAdmin}
528     */
529    public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
530        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
531
532        // Add admin1.
533
534        dpm.setActiveAdmin(admin1, /* replace =*/ false);
535
536        assertTrue(dpm.isAdminActive(admin1));
537        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
538
539        // Different user, but should work, because caller has proper permissions.
540        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
541
542        // Change the caller, and call into DPMS directly with a different user-id.
543        mContext.binder.callingUid = 1234567;
544
545        dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
546        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
547
548        // TODO DO Still can't be removed in this case.
549    }
550
551    /**
552     * Test for:
553     * {@link DevicePolicyManager#removeActiveAdmin}
554     */
555    public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
556        // Need MANAGE_DEVICE_ADMINS for setActiveAdmin.  We'll remove it later.
557        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
558
559        // Add admin1.
560
561        dpm.setActiveAdmin(admin1, /* replace =*/ false);
562
563        assertTrue(dpm.isAdminActive(admin1));
564        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
565
566        // Broadcast from saveSettingsLocked().
567        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
568                MockUtils.checkIntentAction(
569                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
570                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
571
572        // Remove.  No permissions, but same user, so it'll work.
573        mContext.callerPermissions.clear();
574        dpm.removeActiveAdmin(admin1);
575
576        verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
577                MockUtils.checkIntentAction(
578                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
579                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
580                isNull(String.class),
581                any(BroadcastReceiver.class),
582                eq(dpms.mHandler),
583                eq(Activity.RESULT_OK),
584                isNull(String.class),
585                isNull(Bundle.class));
586
587        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
588
589        // Again broadcast from saveSettingsLocked().
590        verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
591                MockUtils.checkIntentAction(
592                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
593                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
594
595        // TODO Check other internal calls.
596    }
597
598    /**
599     * Test for: @{link DevicePolicyManager#setActivePasswordState}
600     *
601     * Validates that when the password for a user changes, the notification broadcast intent
602     * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
603     * addition to ones in the original user.
604     */
605    public void testSetActivePasswordState_sendToProfiles() throws Exception {
606        mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
607
608        final int MANAGED_PROFILE_USER_ID = 78;
609        final int MANAGED_PROFILE_ADMIN_UID =
610                UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
611
612        // Setup device owner.
613        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
614        mContext.packageName = admin1.getPackageName();
615        setupDeviceOwner();
616
617        // Add a managed profile belonging to the system user.
618        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
619
620        // Change the parent user's password.
621        dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
622
623        // Both the device owner and the managed profile owner should receive this broadcast.
624        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
625        intent.setComponent(admin1);
626        intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
627
628        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
629                MockUtils.checkIntent(intent),
630                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
631        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
632                MockUtils.checkIntent(intent),
633                MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
634    }
635
636    /**
637     * Test for: @{link DevicePolicyManager#setActivePasswordState}
638     *
639     * Validates that when the password for a managed profile changes, the notification broadcast
640     * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
641     * its parent.
642     */
643    public void testSetActivePasswordState_notSentToParent() throws Exception {
644        mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
645
646        final int MANAGED_PROFILE_USER_ID = 78;
647        final int MANAGED_PROFILE_ADMIN_UID =
648                UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
649
650        // Setup device owner.
651        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
652        mContext.packageName = admin1.getPackageName();
653        doReturn(true).when(mContext.lockPatternUtils)
654                .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
655        setupDeviceOwner();
656
657        // Add a managed profile belonging to the system user.
658        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
659
660        // Change the profile's password.
661        dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
662
663        // Both the device owner and the managed profile owner should receive this broadcast.
664        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
665        intent.setComponent(admin1);
666        intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
667
668        verify(mContext.spiedContext, never()).sendBroadcastAsUser(
669                MockUtils.checkIntent(intent),
670                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
671        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
672                MockUtils.checkIntent(intent),
673                MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
674    }
675    /**
676     * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
677     */
678    public void testSetDeviceOwner() throws Exception {
679        setDeviceOwner();
680
681        // Try to set a profile owner on the same user, which should fail.
682        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
683        dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
684        try {
685            dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
686            fail("IllegalStateException not thrown");
687        } catch (IllegalStateException expected) {
688            assertTrue("Message was: " + expected.getMessage(),
689                    expected.getMessage().contains("already has a device owner"));
690        }
691
692        // DO admin can't be deactivated.
693        dpm.removeActiveAdmin(admin1);
694        assertTrue(dpm.isAdminActive(admin1));
695
696        // TODO Test getDeviceOwnerName() too. To do so, we need to change
697        // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
698    }
699
700    private void setDeviceOwner() throws Exception {
701        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
702        mContext.callerPermissions.add(permission.MANAGE_USERS);
703        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
704        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
705
706        // In this test, change the caller user to "system".
707        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
708
709        // Make sure admin1 is installed on system user.
710        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
711
712        // Check various get APIs.
713        checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
714
715        // DO needs to be an DA.
716        dpm.setActiveAdmin(admin1, /* replace =*/ false);
717
718        // Fire!
719        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
720
721        // getDeviceOwnerComponent should return the admin1 component.
722        assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
723        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
724
725        // Check various get APIs.
726        checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
727
728        // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
729        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
730        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
731        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
732
733        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
734
735        // Verify internal calls.
736        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
737                eq(admin1.getPackageName()));
738
739        // TODO We should check if the caller has called clearCallerIdentity().
740        verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
741                eq(UserHandle.USER_SYSTEM), eq(false));
742
743        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
744                MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
745                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
746
747        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
748    }
749
750    private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
751        final int origCallingUser = mContext.binder.callingUid;
752        final List origPermissions = new ArrayList(mContext.callerPermissions);
753        mContext.callerPermissions.clear();
754
755        mContext.callerPermissions.add(permission.MANAGE_USERS);
756
757        mContext.binder.callingUid = Process.SYSTEM_UID;
758
759        // TODO Test getDeviceOwnerName() too.  To do so, we need to change
760        // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
761        if (hasDeviceOwner) {
762            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
763            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
764            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
765
766            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
767            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
768            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
769        } else {
770            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
771            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
772            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
773
774            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
775            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
776            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
777        }
778
779        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
780        if (hasDeviceOwner) {
781            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
782            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
783            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
784
785            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
786            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
787            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
788        } else {
789            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
790            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
791            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
792
793            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
794            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
795            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
796        }
797
798        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
799        // Still with MANAGE_USERS.
800        assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
801        assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
802        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
803
804        if (hasDeviceOwner) {
805            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
806            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
807            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
808        } else {
809            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
810            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
811            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
812        }
813
814        mContext.binder.callingUid = Process.SYSTEM_UID;
815        mContext.callerPermissions.remove(permission.MANAGE_USERS);
816        // System can still call "OnAnyUser" without MANAGE_USERS.
817        if (hasDeviceOwner) {
818            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
819            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
820            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
821
822            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
823            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
824            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
825        } else {
826            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
827            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
828            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
829
830            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
831            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
832            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
833        }
834
835        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
836        // Still no MANAGE_USERS.
837        if (hasDeviceOwner) {
838            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
839            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
840            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
841        } else {
842            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
843            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
844            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
845        }
846
847        try {
848            dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
849            fail();
850        } catch (SecurityException expected) {
851        }
852        try {
853            dpm.getDeviceOwnerComponentOnAnyUser();
854            fail();
855        } catch (SecurityException expected) {
856        }
857        try {
858            dpm.getDeviceOwnerUserId();
859            fail();
860        } catch (SecurityException expected) {
861        }
862        try {
863            dpm.getDeviceOwnerNameOnAnyUser();
864            fail();
865        } catch (SecurityException expected) {
866        }
867
868        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
869        // Still no MANAGE_USERS.
870        assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
871        assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
872        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
873
874        try {
875            dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
876            fail();
877        } catch (SecurityException expected) {
878        }
879        try {
880            dpm.getDeviceOwnerComponentOnAnyUser();
881            fail();
882        } catch (SecurityException expected) {
883        }
884        try {
885            dpm.getDeviceOwnerUserId();
886            fail();
887        } catch (SecurityException expected) {
888        }
889        try {
890            dpm.getDeviceOwnerNameOnAnyUser();
891            fail();
892        } catch (SecurityException expected) {
893        }
894
895        // Restore.
896        mContext.binder.callingUid = origCallingUser;
897        mContext.callerPermissions.addAll(origPermissions);
898    }
899
900
901    /**
902     * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
903     */
904    public void testSetDeviceOwner_noSuchPackage() {
905        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
906        mContext.callerPermissions.add(permission.MANAGE_USERS);
907        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
908        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
909
910        // Call from a process on the system user.
911        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
912
913        try {
914            dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
915            fail("Didn't throw IllegalArgumentException");
916        } catch (IllegalArgumentException expected) {
917            assertTrue("Message was: " + expected.getMessage(),
918                    expected.getMessage().contains("Invalid component"));
919        }
920    }
921
922    public void testSetDeviceOwner_failures() throws Exception {
923        // TODO Test more failure cases.  Basically test all chacks in enforceCanSetDeviceOwner().
924    }
925
926    public void testClearDeviceOwner() throws Exception {
927        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
928        mContext.callerPermissions.add(permission.MANAGE_USERS);
929        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
930        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
931
932        // Set admin1 as a DA to the secondary user.
933        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
934
935        dpm.setActiveAdmin(admin1, /* replace =*/ false);
936
937        // Set admin 1 as the DO to the system user.
938
939        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
940        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
941        dpm.setActiveAdmin(admin1, /* replace =*/ false);
942        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
943
944        // Verify internal calls.
945        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
946                eq(admin1.getPackageName()));
947
948        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
949
950        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
951        when(mContext.userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
952                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
953
954        assertTrue(dpm.isAdminActive(admin1));
955        assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
956
957        // Set up other mocks.
958        when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
959
960        // Now call clear.
961        doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
962                eq(admin1.getPackageName()),
963                anyInt());
964
965        // But first pretend the user is locked.  Then it should fail.
966        when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
967        try {
968            dpm.clearDeviceOwnerApp(admin1.getPackageName());
969            fail("Didn't throw IllegalStateException");
970        } catch (IllegalStateException expected) {
971            MoreAsserts.assertContainsRegex(
972                    "User must be running and unlocked", expected.getMessage());
973        }
974
975        when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
976        reset(mContext.userManagerInternal);
977        dpm.clearDeviceOwnerApp(admin1.getPackageName());
978
979        // Now DO shouldn't be set.
980        assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
981
982        verify(mContext.userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
983                eq(false),
984                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
985
986        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
987                eq(UserHandle.USER_SYSTEM),
988                eq(null),
989                eq(true), eq(CAMERA_NOT_DISABLED));
990
991        assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
992
993        // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
994        // and once for clearing it.
995        verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
996                MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
997                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
998        // TODO Check other calls.
999    }
1000
1001    public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1002        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1003        mContext.callerPermissions.add(permission.MANAGE_USERS);
1004        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1005        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1006
1007        // Set admin1 as a DA to the secondary user.
1008        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1009
1010        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1011
1012        // Set admin 1 as the DO to the system user.
1013
1014        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1015        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1016        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1017        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1018
1019        // Verify internal calls.
1020        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
1021                eq(admin1.getPackageName()));
1022
1023        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1024
1025        // Now call clear from the secondary user, which should throw.
1026        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1027
1028        // Now call clear.
1029        doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
1030                eq(admin1.getPackageName()),
1031                anyInt());
1032        try {
1033            dpm.clearDeviceOwnerApp(admin1.getPackageName());
1034            fail("Didn't throw");
1035        } catch (SecurityException e) {
1036            assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1037        }
1038
1039        // DO shouldn't be removed.
1040        assertTrue(dpm.isDeviceManaged());
1041    }
1042
1043    public void testSetProfileOwner() throws Exception {
1044        setAsProfileOwner(admin1);
1045
1046        // PO admin can't be deactivated.
1047        dpm.removeActiveAdmin(admin1);
1048        assertTrue(dpm.isAdminActive(admin1));
1049
1050        // Try setting DO on the same user, which should fail.
1051        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1052        dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1053        try {
1054            dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1055            fail("IllegalStateException not thrown");
1056        } catch (IllegalStateException expected) {
1057            assertTrue("Message was: " + expected.getMessage(),
1058                    expected.getMessage().contains("already has a profile owner"));
1059        }
1060    }
1061
1062    public void testClearProfileOwner() throws Exception {
1063        setAsProfileOwner(admin1);
1064
1065        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1066
1067        assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1068        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1069
1070        // First try when the user is locked, which should fail.
1071        when(mContext.userManager.isUserUnlocked(anyInt()))
1072                .thenReturn(false);
1073        try {
1074            dpm.clearProfileOwner(admin1);
1075            fail("Didn't throw IllegalStateException");
1076        } catch (IllegalStateException expected) {
1077            MoreAsserts.assertContainsRegex(
1078                    "User must be running and unlocked", expected.getMessage());
1079        }
1080        // Clear, really.
1081        when(mContext.userManager.isUserUnlocked(anyInt()))
1082                .thenReturn(true);
1083        dpm.clearProfileOwner(admin1);
1084
1085        // Check
1086        assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
1087        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
1088    }
1089
1090    public void testSetProfileOwner_failures() throws Exception {
1091        // TODO Test more failure cases.  Basically test all chacks in enforceCanSetProfileOwner().
1092    }
1093
1094    public void testGetDeviceOwnerAdminLocked() throws Exception {
1095        checkDeviceOwnerWithMultipleDeviceAdmins();
1096    }
1097
1098    private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1099        // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1100        // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1101        // make sure it gets the right component from the right user.
1102
1103        final int ANOTHER_USER_ID = 100;
1104        final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1105
1106        mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1107
1108        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1109        mContext.callerPermissions.add(permission.MANAGE_USERS);
1110        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1111        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1112
1113        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1114
1115        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1116
1117        // Make sure the admin packge is installed to each user.
1118        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1119        setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1120
1121        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1122        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1123
1124        setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1125
1126
1127        // Set active admins to the users.
1128        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1129        dpm.setActiveAdmin(admin3, /* replace =*/ false);
1130
1131        dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1132        dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1133
1134        dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1135
1136        // Set DO on the first non-system user.
1137        mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1138        assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1139
1140        assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1141
1142        // Then check getDeviceOwnerAdminLocked().
1143        assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1144        assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1145    }
1146
1147    /**
1148     * This essentially tests
1149     * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1150     * private.)
1151     *
1152     * We didn't use to persist the DO component class name, but now we do, and the above method
1153     * finds the right component from a package name upon migration.
1154     */
1155    public void testDeviceOwnerMigration() throws Exception {
1156        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1157        checkDeviceOwnerWithMultipleDeviceAdmins();
1158
1159        // Overwrite the device owner setting and clears the clas name.
1160        dpms.mOwners.setDeviceOwner(
1161                new ComponentName(admin2.getPackageName(), ""),
1162                "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1163        dpms.mOwners.writeDeviceOwner();
1164
1165        // Make sure the DO component name doesn't have a class name.
1166        assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
1167
1168        // Then create a new DPMS to have it load the settings from files.
1169        when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1170                .thenReturn(new Bundle());
1171        initializeDpms();
1172
1173        // Now the DO component name is a full name.
1174        // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1175        // DO.
1176        assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1177    }
1178
1179    public void testSetGetApplicationRestriction() {
1180        setAsProfileOwner(admin1);
1181        mContext.packageName = admin1.getPackageName();
1182
1183        {
1184            Bundle rest = new Bundle();
1185            rest.putString("KEY_STRING", "Foo1");
1186            dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1187        }
1188
1189        {
1190            Bundle rest = new Bundle();
1191            rest.putString("KEY_STRING", "Foo2");
1192            dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1193        }
1194
1195        {
1196            Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1197            assertNotNull(returned);
1198            assertEquals(returned.size(), 1);
1199            assertEquals(returned.get("KEY_STRING"), "Foo1");
1200        }
1201
1202        {
1203            Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1204            assertNotNull(returned);
1205            assertEquals(returned.size(), 1);
1206            assertEquals(returned.get("KEY_STRING"), "Foo2");
1207        }
1208
1209        dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1210        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1211    }
1212
1213    /**
1214     * Setup a package in the package manager mock. Useful for faking installed applications.
1215     *
1216     * @param packageName the name of the package to be setup
1217     * @param appId the application ID to be given to the package
1218     * @return the UID of the package as known by the mock package manager
1219     */
1220    private int setupPackageInPackageManager(final String packageName, final int appId)
1221            throws Exception {
1222        // Make the PackageManager return the package instead of throwing a NameNotFoundException
1223        final PackageInfo pi = new PackageInfo();
1224        pi.applicationInfo = new ApplicationInfo();
1225        pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1226        doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1227                eq(packageName),
1228                anyInt(),
1229                eq(DpmMockContext.CALLER_USER_HANDLE));
1230        // Setup application UID with the PackageManager
1231        final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1232        doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1233                eq(packageName),
1234                eq(DpmMockContext.CALLER_USER_HANDLE));
1235        // Associate packageName to uid
1236        doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1237        doReturn(new String[]{packageName})
1238            .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1239        return uid;
1240    }
1241
1242    public void testCertificateDisclosure() throws Exception {
1243        final int userId = DpmMockContext.CALLER_USER_HANDLE;
1244        final UserHandle user = UserHandle.of(userId);
1245
1246        mContext.applicationInfo = new ApplicationInfo();
1247        mContext.callerPermissions.add(permission.MANAGE_USERS);
1248        mContext.packageName = "com.android.frameworks.servicestests";
1249        mContext.userContexts.put(user, mContext);
1250        when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1251
1252        StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1253        StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
1254
1255        final String TEST_STRING = "Test for exactly 2 certs out of 4";
1256        doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1257
1258        // Given that we have exactly one certificate installed,
1259        when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1260        // when that certificate is approved,
1261        dpms.approveCaCert(oneCert.getList().get(0), userId, true);
1262        // a notification should not be shown.
1263        verify(mContext.notificationManager, timeout(1000))
1264                .cancelAsUser(anyString(), anyInt(), eq(user));
1265
1266        // Given that we have four certificates installed,
1267        when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1268        // when two of them are approved (one of them approved twice hence no action),
1269        dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1270        dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
1271        // a notification should be shown saying that there are two certificates left to approve.
1272        verify(mContext.notificationManager, timeout(1000))
1273                .notifyAsUser(anyString(), anyInt(), argThat(
1274                        new BaseMatcher<Notification>() {
1275                            @Override
1276                            public boolean matches(Object item) {
1277                                final Notification noti = (Notification) item;
1278                                return TEST_STRING.equals(
1279                                        noti.extras.getString(Notification.EXTRA_TITLE));
1280                            }
1281                            @Override
1282                            public void describeTo(Description description) {
1283                                description.appendText(
1284                                        "Notification{title=\"" + TEST_STRING + "\"}");
1285                            }
1286                        }), eq(user));
1287    }
1288
1289    /**
1290     * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1291     * privileges can acually be exercised by a delegate are not covered here.
1292     */
1293    public void testDelegation() throws Exception {
1294        setAsProfileOwner(admin1);
1295
1296        final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1297
1298        // Given two packages
1299        final String CERT_DELEGATE = "com.delegate.certs";
1300        final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1301        final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1302        final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1303                20989);
1304
1305        // On delegation
1306        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1307        mContext.packageName = admin1.getPackageName();
1308        dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1309        dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1310
1311        // DPMS correctly stores and retrieves the delegates
1312        DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1313        assertEquals(2, policy.mDelegationMap.size());
1314        MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1315            DELEGATION_CERT_INSTALL);
1316        MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1317            DELEGATION_CERT_INSTALL);
1318        assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1319        MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1320            DELEGATION_APP_RESTRICTIONS);
1321        MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1322            DELEGATION_APP_RESTRICTIONS);
1323        assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1324
1325        // On calling install certificate APIs from an unauthorized process
1326        mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1327        mContext.packageName = RESTRICTIONS_DELEGATE;
1328
1329        // DPMS throws a SecurityException
1330        try {
1331            dpm.installCaCert(null, null);
1332            fail("Didn't throw SecurityException on unauthorized access");
1333        } catch (SecurityException expected) {
1334        }
1335
1336        // On calling install certificate APIs from an authorized process
1337        mContext.binder.callingUid = CERT_DELEGATE_UID;
1338        mContext.packageName = CERT_DELEGATE;
1339
1340        // DPMS executes without a SecurityException
1341        try {
1342            dpm.installCaCert(null, null);
1343        } catch (SecurityException unexpected) {
1344            fail("Threw SecurityException on authorized access");
1345        } catch (NullPointerException expected) {
1346        }
1347
1348        // On removing a delegate
1349        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1350        mContext.packageName = admin1.getPackageName();
1351        dpm.setCertInstallerPackage(admin1, null);
1352
1353        // DPMS does not allow access to ex-delegate
1354        mContext.binder.callingUid = CERT_DELEGATE_UID;
1355        mContext.packageName = CERT_DELEGATE;
1356        try {
1357            dpm.installCaCert(null, null);
1358            fail("Didn't throw SecurityException on unauthorized access");
1359        } catch (SecurityException expected) {
1360        }
1361
1362        // But still allows access to other existing delegates
1363        mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1364        mContext.packageName = RESTRICTIONS_DELEGATE;
1365        try {
1366            dpm.getApplicationRestrictions(null, "pkg");
1367        } catch (SecurityException expected) {
1368            fail("Threw SecurityException on authorized access");
1369        }
1370    }
1371
1372    public void testApplicationRestrictionsManagingApp() throws Exception {
1373        setAsProfileOwner(admin1);
1374
1375        final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
1376        final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1377        final int appRestrictionsManagerAppId = 20987;
1378        final int appRestrictionsManagerUid = setupPackageInPackageManager(
1379                appRestrictionsManagerPackage, appRestrictionsManagerAppId);
1380
1381        // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1382        // delegated that permission yet.
1383        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1384        mContext.packageName = admin1.getPackageName();
1385        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1386        Bundle rest = new Bundle();
1387        rest.putString("KEY_STRING", "Foo1");
1388        try {
1389            dpm.setApplicationRestrictions(null, "pkg1", rest);
1390            fail("Didn't throw expected SecurityException");
1391        } catch (SecurityException expected) {
1392            MoreAsserts.assertContainsRegex(
1393                    "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1394                    expected.getMessage());
1395        }
1396        try {
1397            dpm.getApplicationRestrictions(null, "pkg1");
1398            fail("Didn't throw expected SecurityException");
1399        } catch (SecurityException expected) {
1400            MoreAsserts.assertContainsRegex(
1401                    "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1402                    expected.getMessage());
1403        }
1404
1405        // Check via the profile owner that no restrictions were set.
1406        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1407        mContext.packageName = admin1.getPackageName();
1408        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1409
1410        // Check the API does not allow setting a non-existent package
1411        try {
1412            dpm.setApplicationRestrictionsManagingPackage(admin1,
1413                    nonExistAppRestrictionsManagerPackage);
1414            fail("Non-existent app set as app restriction manager.");
1415        } catch (PackageManager.NameNotFoundException expected) {
1416            MoreAsserts.assertContainsRegex(
1417                    nonExistAppRestrictionsManagerPackage, expected.getMessage());
1418        }
1419
1420        // Let appRestrictionsManagerPackage manage app restrictions
1421        dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1422        assertEquals(appRestrictionsManagerPackage,
1423                dpm.getApplicationRestrictionsManagingPackage(admin1));
1424
1425        // Now that package should be able to set and retrieve app restrictions.
1426        mContext.binder.callingUid = appRestrictionsManagerUid;
1427        mContext.packageName = appRestrictionsManagerPackage;
1428        assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1429        dpm.setApplicationRestrictions(null, "pkg1", rest);
1430        Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1431        assertEquals(1, returned.size(), 1);
1432        assertEquals("Foo1", returned.get("KEY_STRING"));
1433
1434        // The same app running on a separate user shouldn't be able to manage app restrictions.
1435        mContext.binder.callingUid = UserHandle.getUid(
1436                UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1437        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1438        try {
1439            dpm.setApplicationRestrictions(null, "pkg1", rest);
1440            fail("Didn't throw expected SecurityException");
1441        } catch (SecurityException expected) {
1442            MoreAsserts.assertContainsRegex(
1443                    "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1444                    expected.getMessage());
1445        }
1446
1447        // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1448        // too.
1449        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1450        mContext.packageName = admin1.getPackageName();
1451        assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1452        dpm.setApplicationRestrictions(admin1, "pkg1", null);
1453        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1454
1455        // Removing the ability for the package to manage app restrictions.
1456        dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1457        assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1458        mContext.binder.callingUid = appRestrictionsManagerUid;
1459        mContext.packageName = appRestrictionsManagerPackage;
1460        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1461        try {
1462            dpm.setApplicationRestrictions(null, "pkg1", null);
1463            fail("Didn't throw expected SecurityException");
1464        } catch (SecurityException expected) {
1465            MoreAsserts.assertContainsRegex(
1466                    "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1467                    expected.getMessage());
1468        }
1469    }
1470
1471    public void testSetUserRestriction_asDo() throws Exception {
1472        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1473        mContext.callerPermissions.add(permission.MANAGE_USERS);
1474        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1475        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1476
1477        // First, set DO.
1478
1479        // Call from a process on the system user.
1480        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1481
1482        // Make sure admin1 is installed on system user.
1483        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1484
1485        // Call.
1486        dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1487        assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1488                UserHandle.USER_SYSTEM));
1489
1490        // Check that the user restrictions that are enabled by default are set. Then unset them.
1491        String[] defaultRestrictions = UserRestrictionsUtils
1492                .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1493        DpmTestUtils.assertRestrictions(
1494                DpmTestUtils.newRestrictions(defaultRestrictions),
1495                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1496        );
1497        DpmTestUtils.assertRestrictions(
1498                DpmTestUtils.newRestrictions(defaultRestrictions),
1499                dpm.getUserRestrictions(admin1)
1500        );
1501        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1502                eq(UserHandle.USER_SYSTEM),
1503                MockUtils.checkUserRestrictions(defaultRestrictions),
1504                eq(true) /* isDeviceOwner */,
1505                eq(CAMERA_NOT_DISABLED)
1506        );
1507        reset(mContext.userManagerInternal);
1508
1509        for (String restriction : defaultRestrictions) {
1510            dpm.clearUserRestriction(admin1, restriction);
1511        }
1512
1513        assertNoDeviceOwnerRestrictions();
1514        reset(mContext.userManagerInternal);
1515
1516        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1517        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1518                eq(UserHandle.USER_SYSTEM),
1519                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1520                eq(true), eq(CAMERA_NOT_DISABLED));
1521        reset(mContext.userManagerInternal);
1522
1523        dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1524        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1525                eq(UserHandle.USER_SYSTEM),
1526                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1527                        UserManager.DISALLOW_ADD_USER),
1528                eq(true), eq(CAMERA_NOT_DISABLED));
1529        reset(mContext.userManagerInternal);
1530
1531        DpmTestUtils.assertRestrictions(
1532                DpmTestUtils.newRestrictions(
1533                        UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1534                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1535        );
1536        DpmTestUtils.assertRestrictions(
1537                DpmTestUtils.newRestrictions(
1538                        UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1539                dpm.getUserRestrictions(admin1)
1540        );
1541
1542        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1543        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1544                eq(UserHandle.USER_SYSTEM),
1545                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1546                eq(true), eq(CAMERA_NOT_DISABLED));
1547        reset(mContext.userManagerInternal);
1548
1549        DpmTestUtils.assertRestrictions(
1550                DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1551                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1552        );
1553        DpmTestUtils.assertRestrictions(
1554                DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1555                dpm.getUserRestrictions(admin1)
1556        );
1557
1558        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1559        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1560                eq(UserHandle.USER_SYSTEM),
1561                MockUtils.checkUserRestrictions(),
1562                eq(true), eq(CAMERA_NOT_DISABLED));
1563        reset(mContext.userManagerInternal);
1564
1565        assertNoDeviceOwnerRestrictions();
1566
1567        // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1568        // DO sets them, the scope is global.
1569        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1570        reset(mContext.userManagerInternal);
1571        dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1572        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1573                eq(UserHandle.USER_SYSTEM),
1574                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1575                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1576                eq(true), eq(CAMERA_NOT_DISABLED));
1577        reset(mContext.userManagerInternal);
1578
1579        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1580        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1581        reset(mContext.userManagerInternal);
1582
1583        // More tests.
1584        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1585        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1586                eq(UserHandle.USER_SYSTEM),
1587                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1588                eq(true), eq(CAMERA_NOT_DISABLED));
1589        reset(mContext.userManagerInternal);
1590
1591        dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1592        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1593                eq(UserHandle.USER_SYSTEM),
1594                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1595                        UserManager.DISALLOW_ADD_USER),
1596                eq(true), eq(CAMERA_NOT_DISABLED));
1597        reset(mContext.userManagerInternal);
1598
1599        dpm.setCameraDisabled(admin1, true);
1600        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1601                eq(UserHandle.USER_SYSTEM),
1602                // DISALLOW_CAMERA will be applied to both local and global.
1603                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1604                        UserManager.DISALLOW_ADD_USER),
1605                eq(true), eq(CAMERA_DISABLED_GLOBALLY));
1606        reset(mContext.userManagerInternal);
1607
1608        // Set up another DA and let it disable camera.  Now DISALLOW_CAMERA will only be applied
1609        // locally.
1610        dpm.setCameraDisabled(admin1, false);
1611        reset(mContext.userManagerInternal);
1612
1613        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1614        dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1615        dpm.setCameraDisabled(admin2, true);
1616
1617        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1618                eq(UserHandle.USER_SYSTEM),
1619                // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
1620                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1621                        UserManager.DISALLOW_ADD_USER),
1622                eq(true), eq(CAMERA_DISABLED_LOCALLY));
1623        reset(mContext.userManagerInternal);
1624        // TODO Make sure restrictions are written to the file.
1625    }
1626
1627    public void testSetUserRestriction_asPo() {
1628        setAsProfileOwner(admin1);
1629
1630        DpmTestUtils.assertRestrictions(
1631                DpmTestUtils.newRestrictions(),
1632                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1633                        .ensureUserRestrictions()
1634        );
1635
1636        dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1637        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1638                eq(DpmMockContext.CALLER_USER_HANDLE),
1639                MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1640                eq(false), eq(CAMERA_NOT_DISABLED));
1641        reset(mContext.userManagerInternal);
1642
1643        dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1644        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1645                eq(DpmMockContext.CALLER_USER_HANDLE),
1646                MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1647                        UserManager.DISALLOW_OUTGOING_CALLS),
1648                eq(false), eq(CAMERA_NOT_DISABLED));
1649        reset(mContext.userManagerInternal);
1650
1651        DpmTestUtils.assertRestrictions(
1652                DpmTestUtils.newRestrictions(
1653                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1654                        UserManager.DISALLOW_OUTGOING_CALLS
1655                ),
1656                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1657                        .ensureUserRestrictions()
1658        );
1659        DpmTestUtils.assertRestrictions(
1660                DpmTestUtils.newRestrictions(
1661                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1662                        UserManager.DISALLOW_OUTGOING_CALLS
1663                ),
1664                dpm.getUserRestrictions(admin1)
1665        );
1666
1667        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1668        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1669                eq(DpmMockContext.CALLER_USER_HANDLE),
1670                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1671                eq(false), eq(CAMERA_NOT_DISABLED));
1672        reset(mContext.userManagerInternal);
1673
1674        DpmTestUtils.assertRestrictions(
1675                DpmTestUtils.newRestrictions(
1676                        UserManager.DISALLOW_OUTGOING_CALLS
1677                ),
1678                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1679                        .ensureUserRestrictions()
1680        );
1681        DpmTestUtils.assertRestrictions(
1682                DpmTestUtils.newRestrictions(
1683                        UserManager.DISALLOW_OUTGOING_CALLS
1684                ),
1685                dpm.getUserRestrictions(admin1)
1686        );
1687
1688        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1689        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1690                eq(DpmMockContext.CALLER_USER_HANDLE),
1691                MockUtils.checkUserRestrictions(),
1692                eq(false), eq(CAMERA_NOT_DISABLED));
1693        reset(mContext.userManagerInternal);
1694
1695        DpmTestUtils.assertRestrictions(
1696                DpmTestUtils.newRestrictions(),
1697                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1698                        .ensureUserRestrictions()
1699        );
1700        DpmTestUtils.assertRestrictions(
1701                DpmTestUtils.newRestrictions(),
1702                dpm.getUserRestrictions(admin1)
1703        );
1704
1705        // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1706        // though when DO sets them they'll be applied globally.
1707        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1708        reset(mContext.userManagerInternal);
1709        dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1710        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1711                eq(DpmMockContext.CALLER_USER_HANDLE),
1712                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1713                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1714                eq(false), eq(CAMERA_NOT_DISABLED));
1715        reset(mContext.userManagerInternal);
1716
1717        dpm.setCameraDisabled(admin1, true);
1718        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1719                eq(DpmMockContext.CALLER_USER_HANDLE),
1720                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1721                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1722                eq(false), eq(CAMERA_DISABLED_LOCALLY));
1723        reset(mContext.userManagerInternal);
1724
1725        // TODO Make sure restrictions are written to the file.
1726    }
1727
1728
1729    public void testDefaultEnabledUserRestrictions() throws Exception {
1730        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1731        mContext.callerPermissions.add(permission.MANAGE_USERS);
1732        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1733        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1734
1735        // First, set DO.
1736
1737        // Call from a process on the system user.
1738        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1739
1740        // Make sure admin1 is installed on system user.
1741        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1742
1743        dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1744        assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1745                UserHandle.USER_SYSTEM));
1746
1747        // Check that the user restrictions that are enabled by default are set. Then unset them.
1748        String[] defaultRestrictions = UserRestrictionsUtils
1749                .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1750        assertTrue(defaultRestrictions.length > 0);
1751        DpmTestUtils.assertRestrictions(
1752                DpmTestUtils.newRestrictions(defaultRestrictions),
1753                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1754        );
1755        DpmTestUtils.assertRestrictions(
1756                DpmTestUtils.newRestrictions(defaultRestrictions),
1757                dpm.getUserRestrictions(admin1)
1758        );
1759        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1760                eq(UserHandle.USER_SYSTEM),
1761                MockUtils.checkUserRestrictions(defaultRestrictions),
1762                eq(true) /* isDeviceOwner */,
1763                eq(CAMERA_NOT_DISABLED)
1764        );
1765        reset(mContext.userManagerInternal);
1766
1767        for (String restriction : defaultRestrictions) {
1768            dpm.clearUserRestriction(admin1, restriction);
1769        }
1770
1771        assertNoDeviceOwnerRestrictions();
1772
1773        // Initialize DPMS again and check that the user restriction wasn't enabled again.
1774        reset(mContext.userManagerInternal);
1775        initializeDpms();
1776        assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1777        assertNotNull(dpms.getDeviceOwnerAdminLocked());
1778
1779        assertNoDeviceOwnerRestrictions();
1780
1781        // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1782        // is set as it wasn't enabled during setDeviceOwner.
1783        final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1784        assertFalse(UserRestrictionsUtils
1785                .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1786        UserRestrictionsUtils
1787                .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1788        try {
1789            reset(mContext.userManagerInternal);
1790            initializeDpms();
1791            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1792            assertNotNull(dpms.getDeviceOwnerAdminLocked());
1793
1794            DpmTestUtils.assertRestrictions(
1795                DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1796                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1797            );
1798            DpmTestUtils.assertRestrictions(
1799                DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1800                dpm.getUserRestrictions(admin1)
1801            );
1802            verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1803                eq(UserHandle.USER_SYSTEM),
1804                MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
1805                eq(true) /* isDeviceOwner */,
1806                eq(CAMERA_NOT_DISABLED)
1807            );
1808            reset(mContext.userManagerInternal);
1809
1810            // Remove the restriction.
1811            dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1812
1813            // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1814            initializeDpms();
1815            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1816            assertNotNull(dpms.getDeviceOwnerAdminLocked());
1817            assertNoDeviceOwnerRestrictions();
1818        } finally {
1819            UserRestrictionsUtils
1820                .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1821        }
1822    }
1823
1824    private void assertNoDeviceOwnerRestrictions() {
1825        DpmTestUtils.assertRestrictions(
1826                DpmTestUtils.newRestrictions(),
1827                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1828        );
1829        DpmTestUtils.assertRestrictions(
1830                DpmTestUtils.newRestrictions(),
1831                dpm.getUserRestrictions(admin1)
1832        );
1833    }
1834
1835    public void testGetMacAddress() throws Exception {
1836        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1837        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1838        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1839
1840        // In this test, change the caller user to "system".
1841        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1842
1843        // Make sure admin1 is installed on system user.
1844        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1845
1846        // Test 1. Caller doesn't have DO or DA.
1847        try {
1848            dpm.getWifiMacAddress(admin1);
1849            fail();
1850        } catch (SecurityException e) {
1851            MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
1852        }
1853
1854        // DO needs to be an DA.
1855        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1856        assertTrue(dpm.isAdminActive(admin1));
1857
1858        // Test 2. Caller has DA, but not DO.
1859        try {
1860            dpm.getWifiMacAddress(admin1);
1861            fail();
1862        } catch (SecurityException e) {
1863            MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
1864        }
1865
1866        // Test 3. Caller has PO, but not DO.
1867        assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1868        try {
1869            dpm.getWifiMacAddress(admin1);
1870            fail();
1871        } catch (SecurityException e) {
1872            MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
1873        }
1874
1875        // Remove PO.
1876        dpm.clearProfileOwner(admin1);
1877        dpm.setActiveAdmin(admin1, false);
1878        // Test 4, Caller is DO now.
1879        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1880
1881        // 4-1.  But no WifiInfo.
1882        assertNull(dpm.getWifiMacAddress(admin1));
1883
1884        // 4-2.  Returns WifiInfo, but with the default MAC.
1885        when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
1886        assertNull(dpm.getWifiMacAddress(admin1));
1887
1888        // 4-3. With a real MAC address.
1889        final WifiInfo wi = new WifiInfo();
1890        wi.setMacAddress("11:22:33:44:55:66");
1891        when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
1892        assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
1893    }
1894
1895    public void testReboot() throws Exception {
1896        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1897        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1898
1899        // In this test, change the caller user to "system".
1900        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1901
1902        // Make sure admin1 is installed on system user.
1903        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1904
1905        // Set admin1 as DA.
1906        dpm.setActiveAdmin(admin1, false);
1907        assertTrue(dpm.isAdminActive(admin1));
1908        try {
1909            dpm.reboot(admin1);
1910            fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1911        } catch (SecurityException expected) {
1912            MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1913        }
1914
1915        // Set admin1 as PO.
1916        assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1917        try {
1918            dpm.reboot(admin1);
1919            fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1920        } catch (SecurityException expected) {
1921            MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1922        }
1923
1924        // Remove PO and add DO.
1925        dpm.clearProfileOwner(admin1);
1926        dpm.setActiveAdmin(admin1, false);
1927        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1928
1929        // admin1 is DO.
1930        // Set current call state of device to ringing.
1931        when(mContext.telephonyManager.getCallState())
1932                .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1933        try {
1934            dpm.reboot(admin1);
1935            fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1936        } catch (IllegalStateException expected) {
1937            MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1938        }
1939
1940        // Set current call state of device to dialing/active.
1941        when(mContext.telephonyManager.getCallState())
1942                .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1943        try {
1944            dpm.reboot(admin1);
1945            fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1946        } catch (IllegalStateException expected) {
1947            MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1948        }
1949
1950        // Set current call state of device to idle.
1951        when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
1952        dpm.reboot(admin1);
1953    }
1954
1955    public void testSetGetSupportText() {
1956        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1957        dpm.setActiveAdmin(admin1, true);
1958        dpm.setActiveAdmin(admin2, true);
1959        mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1960
1961        // Null default support messages.
1962        {
1963            assertNull(dpm.getLongSupportMessage(admin1));
1964            assertNull(dpm.getShortSupportMessage(admin1));
1965            mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1966            assertNull(dpm.getShortSupportMessageForUser(admin1,
1967                    DpmMockContext.CALLER_USER_HANDLE));
1968            assertNull(dpm.getLongSupportMessageForUser(admin1,
1969                    DpmMockContext.CALLER_USER_HANDLE));
1970            mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1971        }
1972
1973        // Only system can call the per user versions.
1974        {
1975            try {
1976                dpm.getShortSupportMessageForUser(admin1,
1977                        DpmMockContext.CALLER_USER_HANDLE);
1978                fail("Only system should be able to call getXXXForUser versions");
1979            } catch (SecurityException expected) {
1980                MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1981            }
1982            try {
1983                dpm.getLongSupportMessageForUser(admin1,
1984                        DpmMockContext.CALLER_USER_HANDLE);
1985                fail("Only system should be able to call getXXXForUser versions");
1986            } catch (SecurityException expected) {
1987                MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1988            }
1989        }
1990
1991        // Can't set message for admin in another uid.
1992        {
1993            mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1994            try {
1995                dpm.setShortSupportMessage(admin1, "Some text");
1996                fail("Admins should only be able to change their own support text.");
1997            } catch (SecurityException expected) {
1998                MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1999            }
2000            mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2001        }
2002
2003        // Set/Get short returns what it sets and other admins text isn't changed.
2004        {
2005            final String supportText = "Some text to test with.";
2006            dpm.setShortSupportMessage(admin1, supportText);
2007            assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2008            assertNull(dpm.getLongSupportMessage(admin1));
2009            assertNull(dpm.getShortSupportMessage(admin2));
2010
2011            mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2012            assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2013                    DpmMockContext.CALLER_USER_HANDLE));
2014            assertNull(dpm.getShortSupportMessageForUser(admin2,
2015                    DpmMockContext.CALLER_USER_HANDLE));
2016            assertNull(dpm.getLongSupportMessageForUser(admin1,
2017                    DpmMockContext.CALLER_USER_HANDLE));
2018            mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2019
2020            dpm.setShortSupportMessage(admin1, null);
2021            assertNull(dpm.getShortSupportMessage(admin1));
2022        }
2023
2024        // Set/Get long returns what it sets and other admins text isn't changed.
2025        {
2026            final String supportText = "Some text to test with.\nWith more text.";
2027            dpm.setLongSupportMessage(admin1, supportText);
2028            assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2029            assertNull(dpm.getShortSupportMessage(admin1));
2030            assertNull(dpm.getLongSupportMessage(admin2));
2031
2032            mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2033            assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2034                    DpmMockContext.CALLER_USER_HANDLE));
2035            assertNull(dpm.getLongSupportMessageForUser(admin2,
2036                    DpmMockContext.CALLER_USER_HANDLE));
2037            assertNull(dpm.getShortSupportMessageForUser(admin1,
2038                    DpmMockContext.CALLER_USER_HANDLE));
2039            mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2040
2041            dpm.setLongSupportMessage(admin1, null);
2042            assertNull(dpm.getLongSupportMessage(admin1));
2043        }
2044    }
2045
2046    public void testCreateAdminSupportIntent() throws Exception {
2047        // Setup device owner.
2048        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2049        setupDeviceOwner();
2050
2051        // Nonexisting permission returns null
2052        Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2053        assertNull(intent);
2054
2055        // Existing permission that is not set returns null
2056        intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2057        assertNull(intent);
2058
2059        // Existing permission that is not set by device/profile owner returns null
2060        when(mContext.userManager.hasUserRestriction(
2061                eq(UserManager.DISALLOW_ADJUST_VOLUME),
2062                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2063                .thenReturn(true);
2064        intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2065        assertNull(intent);
2066
2067        // Permission that is set by device owner returns correct intent
2068        when(mContext.userManager.getUserRestrictionSource(
2069                eq(UserManager.DISALLOW_ADJUST_VOLUME),
2070                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2071                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2072        intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2073        assertNotNull(intent);
2074        assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2075        assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2076                intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2077        assertEquals(admin1,
2078                (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2079        assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2080                intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2081
2082        // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2083        // user restrictions
2084
2085        // Camera is not disabled
2086        intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2087        assertNull(intent);
2088
2089        // Camera is disabled
2090        dpm.setCameraDisabled(admin1, true);
2091        intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2092        assertNotNull(intent);
2093        assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2094                intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2095
2096        // Screen capture is not disabled
2097        intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2098        assertNull(intent);
2099
2100        // Screen capture is disabled
2101        dpm.setScreenCaptureDisabled(admin1, true);
2102        intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2103        assertNotNull(intent);
2104        assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2105                intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2106
2107        // Same checks for different user
2108        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2109        // Camera should be disabled by device owner
2110        intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2111        assertNotNull(intent);
2112        assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2113                intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2114        assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2115                intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2116        // ScreenCapture should not be disabled by device owner
2117        intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2118        assertNull(intent);
2119    }
2120
2121    /**
2122     * Test for:
2123     * {@link DevicePolicyManager#setAffiliationIds}
2124     * {@link DevicePolicyManager#getAffiliationIds}
2125     * {@link DevicePolicyManager#isAffiliatedUser}
2126     */
2127    public void testUserAffiliation() throws Exception {
2128        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2129        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2130        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2131
2132        // Check that the system user is unaffiliated.
2133        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2134        assertFalse(dpm.isAffiliatedUser());
2135
2136        // Set a device owner on the system user. Check that the system user becomes affiliated.
2137        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2138        dpm.setActiveAdmin(admin1, /* replace =*/ false);
2139        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2140        assertTrue(dpm.isAffiliatedUser());
2141        assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
2142
2143        // Install a profile owner. Check that the test user is unaffiliated.
2144        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2145        setAsProfileOwner(admin2);
2146        assertFalse(dpm.isAffiliatedUser());
2147        assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
2148
2149        // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2150        // unaffiliated.
2151        final List<String> userAffiliationIds = new ArrayList<>();
2152        userAffiliationIds.add("red");
2153        userAffiliationIds.add("green");
2154        userAffiliationIds.add("blue");
2155        dpm.setAffiliationIds(admin2, userAffiliationIds);
2156        MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
2157        assertFalse(dpm.isAffiliatedUser());
2158
2159        // Have the device owner specify a set of affiliation ids that do not intersect with those
2160        // specified by the profile owner. Check that the test user remains unaffiliated.
2161        final List<String> deviceAffiliationIds = new ArrayList<>();
2162        deviceAffiliationIds.add("cyan");
2163        deviceAffiliationIds.add("yellow");
2164        deviceAffiliationIds.add("magenta");
2165        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2166        dpm.setAffiliationIds(admin1, deviceAffiliationIds);
2167        MoreAsserts.assertContentsInAnyOrder(
2168            dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
2169        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2170        assertFalse(dpm.isAffiliatedUser());
2171
2172        // Have the profile owner specify a set of affiliation ids that intersect with those
2173        // specified by the device owner. Check that the test user becomes affiliated.
2174        userAffiliationIds.add("yellow");
2175        dpm.setAffiliationIds(admin2, userAffiliationIds);
2176        MoreAsserts.assertContentsInAnyOrder(
2177            dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
2178        assertTrue(dpm.isAffiliatedUser());
2179
2180        // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2181        dpm.setAffiliationIds(admin2, Collections.emptyList());
2182        assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
2183        assertFalse(dpm.isAffiliatedUser());
2184
2185        // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2186        dpm.setAffiliationIds(admin2, userAffiliationIds);
2187        assertTrue(dpm.isAffiliatedUser());
2188        dpm.clearProfileOwner(admin2);
2189        assertFalse(dpm.isAffiliatedUser());
2190
2191        // Check that the system user remains affiliated.
2192        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2193        assertTrue(dpm.isAffiliatedUser());
2194
2195        // Clear the device owner - the user becomes unaffiliated.
2196        clearDeviceOwner();
2197        assertFalse(dpm.isAffiliatedUser());
2198    }
2199
2200    public void testGetUserProvisioningState_defaultResult() {
2201        assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2202    }
2203
2204    public void testSetUserProvisioningState_permission() throws Exception {
2205        setupProfileOwner();
2206        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2207
2208        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2209                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2210    }
2211
2212    public void testSetUserProvisioningState_unprivileged() throws Exception {
2213        setupProfileOwner();
2214        try {
2215            dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2216                    DpmMockContext.CALLER_USER_HANDLE);
2217            fail("Expected SecurityException");
2218        } catch (SecurityException expected) {
2219        }
2220    }
2221
2222    public void testSetUserProvisioningState_noManagement() {
2223        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2224        try {
2225            dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2226                    DpmMockContext.CALLER_USER_HANDLE);
2227            fail("IllegalStateException expected");
2228        } catch (IllegalStateException e) {
2229            MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2230                    e.getMessage());
2231        }
2232        assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2233    }
2234
2235    public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2236        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2237        setupDeviceOwner();
2238        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2239
2240        exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2241                DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2242                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2243    }
2244
2245    public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2246            throws Exception {
2247        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2248        setupDeviceOwner();
2249        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2250
2251        exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2252                DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2253                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2254    }
2255
2256    public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2257        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2258        setupDeviceOwner();
2259        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2260
2261        exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2262                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2263    }
2264
2265    public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2266            throws Exception {
2267        setupProfileOwner();
2268        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2269
2270        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2271                DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2272                DevicePolicyManager.STATE_USER_UNMANAGED);
2273    }
2274
2275    public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2276            throws Exception {
2277        setupProfileOwner();
2278        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2279
2280        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2281                DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2282                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2283    }
2284
2285    public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2286        setupProfileOwner();
2287        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2288
2289        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2290                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2291    }
2292
2293    public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2294        setupProfileOwner();
2295        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2296
2297        try {
2298            exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2299                    DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2300                    DevicePolicyManager.STATE_USER_UNMANAGED);
2301            fail("Expected IllegalStateException");
2302        } catch (IllegalStateException e) {
2303            MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2304                    e.getMessage());
2305        }
2306    }
2307
2308    public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2309            throws Exception {
2310        setupProfileOwner();
2311        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2312
2313        try {
2314            exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2315                    DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2316                    DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2317            fail("Expected IllegalStateException");
2318        } catch (IllegalStateException e) {
2319            MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2320                    e.getMessage());
2321        }
2322    }
2323
2324    private void exerciseUserProvisioningTransitions(int userId, int... states) {
2325        assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2326        for (int state : states) {
2327            dpm.setUserProvisioningState(state, userId);
2328            assertEquals(state, dpm.getUserProvisioningState());
2329        }
2330    }
2331
2332    private void setupProfileOwner() throws Exception {
2333        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2334
2335        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2336        dpm.setActiveAdmin(admin1, false);
2337        assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2338
2339        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2340    }
2341
2342    private void setupDeviceOwner() throws Exception {
2343        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2344
2345        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2346        dpm.setActiveAdmin(admin1, false);
2347        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2348
2349        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2350    }
2351
2352    public void testSetMaximumTimeToLock() {
2353        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2354
2355        dpm.setActiveAdmin(admin1, /* replace =*/ false);
2356        dpm.setActiveAdmin(admin2, /* replace =*/ false);
2357
2358        reset(mMockContext.powerManagerInternal);
2359        reset(mMockContext.settings);
2360
2361        dpm.setMaximumTimeToLock(admin1, 0);
2362        verifyScreenTimeoutCall(null, false);
2363        reset(mMockContext.powerManagerInternal);
2364        reset(mMockContext.settings);
2365
2366        dpm.setMaximumTimeToLock(admin1, 1);
2367        verifyScreenTimeoutCall(1, true);
2368        reset(mMockContext.powerManagerInternal);
2369        reset(mMockContext.settings);
2370
2371        dpm.setMaximumTimeToLock(admin2, 10);
2372        verifyScreenTimeoutCall(null, false);
2373        reset(mMockContext.powerManagerInternal);
2374        reset(mMockContext.settings);
2375
2376        dpm.setMaximumTimeToLock(admin1, 5);
2377        verifyScreenTimeoutCall(5, true);
2378        reset(mMockContext.powerManagerInternal);
2379        reset(mMockContext.settings);
2380
2381        dpm.setMaximumTimeToLock(admin2, 4);
2382        verifyScreenTimeoutCall(4, true);
2383        reset(mMockContext.powerManagerInternal);
2384        reset(mMockContext.settings);
2385
2386        dpm.setMaximumTimeToLock(admin1, 0);
2387        reset(mMockContext.powerManagerInternal);
2388        reset(mMockContext.settings);
2389
2390        dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2391        verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2392        reset(mMockContext.powerManagerInternal);
2393        reset(mMockContext.settings);
2394
2395        dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2396        verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2397        reset(mMockContext.powerManagerInternal);
2398        reset(mMockContext.settings);
2399
2400        dpm.setMaximumTimeToLock(admin2, 10);
2401        verifyScreenTimeoutCall(10, true);
2402        reset(mMockContext.powerManagerInternal);
2403        reset(mMockContext.settings);
2404
2405        // There's no restriction; shold be set to MAX.
2406        dpm.setMaximumTimeToLock(admin2, 0);
2407        verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2408    }
2409
2410    public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2411        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2412        setupDeviceOwner();
2413        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2414
2415        final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2416        final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2417        final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2418        final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2419                - ONE_MINUTE;
2420
2421        // verify that the minimum timeout cannot be modified on user builds (system property is
2422        // not being read)
2423        mContext.buildMock.isDebuggable = false;
2424
2425        dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2426        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2427        assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2428
2429        verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2430
2431        // restore to the debuggable build state
2432        mContext.buildMock.isDebuggable = true;
2433
2434        // Always return the default (second arg) when getting system property for long type
2435        when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2436                new Answer<Long>() {
2437                    @Override
2438                    public Long answer(InvocationOnMock invocation) throws Throwable {
2439                        return (Long) invocation.getArguments()[1];
2440                    }
2441                }
2442        );
2443
2444        // reset to default (0 means the admin is not participating, so default should be returned)
2445        dpm.setRequiredStrongAuthTimeout(admin1, 0);
2446
2447        // aggregation should be the default if unset by any admin
2448        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2449                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2450
2451        // admin not participating by default
2452        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2453
2454        //clamping from the top
2455        dpm.setRequiredStrongAuthTimeout(admin1,
2456                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2457        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2458                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2459        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2460                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2461
2462        // 0 means the admin is not participating, so default should be returned
2463        dpm.setRequiredStrongAuthTimeout(admin1, 0);
2464        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2465        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2466                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2467
2468        // clamping from the bottom
2469        dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2470        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2471        assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2472
2473        // values within range
2474        dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2475        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2476        assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2477
2478        dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2479        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2480        assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2481
2482        // reset to default
2483        dpm.setRequiredStrongAuthTimeout(admin1, 0);
2484        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2485        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2486                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2487
2488        // negative value
2489        try {
2490            dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2491            fail("Didn't throw IllegalArgumentException");
2492        } catch (IllegalArgumentException iae) {
2493        }
2494    }
2495
2496    private void verifyScreenTimeoutCall(Integer expectedTimeout,
2497            boolean shouldStayOnWhilePluggedInBeCleared) {
2498        if (expectedTimeout == null) {
2499            verify(mMockContext.powerManagerInternal, times(0))
2500                    .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2501        } else {
2502            verify(mMockContext.powerManagerInternal, times(1))
2503                    .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2504        }
2505        // TODO Verify calls to settingsGlobalPutInt.  Tried but somehow mockito threw
2506        // UnfinishedVerificationException.
2507    }
2508
2509    private void setup_DeviceAdminFeatureOff() throws Exception {
2510        when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2511                .thenReturn(false);
2512        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2513                .thenReturn(false);
2514        initializeDpms();
2515        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2516        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2517                .thenReturn(true);
2518        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2519
2520        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2521    }
2522
2523    public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2524        setup_DeviceAdminFeatureOff();
2525        mContext.packageName = admin1.getPackageName();
2526        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2527        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2528        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2529        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2530                false);
2531        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2532    }
2533
2534    public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2535        setup_DeviceAdminFeatureOff();
2536        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2537        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2538                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2539        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2540                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2541        assertCheckProvisioningPreCondition(
2542                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2543                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2544        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2545                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2546    }
2547
2548    private void setup_ManagedProfileFeatureOff() throws Exception {
2549        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2550                .thenReturn(false);
2551        initializeDpms();
2552        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2553        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2554                .thenReturn(true);
2555        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2556
2557        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2558    }
2559
2560    public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2561        setup_ManagedProfileFeatureOff();
2562        mContext.packageName = admin1.getPackageName();
2563        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2564        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2565        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2566        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2567                false);
2568        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2569
2570        // Test again when split user is on
2571        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2572        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2573        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2574        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2575                true);
2576        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2577    }
2578
2579    public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2580        setup_ManagedProfileFeatureOff();
2581        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2582        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2583                DevicePolicyManager.CODE_OK);
2584        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2585                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2586        assertCheckProvisioningPreCondition(
2587                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2588                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2589        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2590                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2591
2592        // Test again when split user is on
2593        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2594        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2595                DevicePolicyManager.CODE_OK);
2596        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2597                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2598        assertCheckProvisioningPreCondition(
2599                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2600                DevicePolicyManager.CODE_OK);
2601        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2602                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2603    }
2604
2605    private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
2606        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2607                .thenReturn(true);
2608        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2609        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2610                .thenReturn(true);
2611        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2612
2613        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2614    }
2615
2616    public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2617        setup_nonSplitUser_firstBoot_primaryUser();
2618        mContext.packageName = admin1.getPackageName();
2619        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2620        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2621        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2622        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2623                false /* because of non-split user */);
2624        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2625                false /* because of non-split user */);
2626    }
2627
2628    public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
2629            throws Exception {
2630        setup_nonSplitUser_firstBoot_primaryUser();
2631        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2632        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2633                DevicePolicyManager.CODE_OK);
2634        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2635                DevicePolicyManager.CODE_OK);
2636        assertCheckProvisioningPreCondition(
2637                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2638                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2639        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2640                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2641    }
2642
2643    private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
2644        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2645                .thenReturn(true);
2646        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2647        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2648                .thenReturn(true);
2649        setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2650
2651        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2652    }
2653
2654    private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2655        setDeviceOwner();
2656        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2657        setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2658    }
2659
2660    private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2661        setup_nonSplitUser_withDo_primaryUser();
2662        final int MANAGED_PROFILE_USER_ID = 18;
2663        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2664        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2665        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2666                false /* we can't remove a managed profile */)).thenReturn(false);
2667        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2668                true)).thenReturn(true);
2669    }
2670
2671    public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2672            throws Exception {
2673        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2674        mContext.packageName = admin1.getPackageName();
2675        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2676        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2677                false/* because of completed device setup */);
2678        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2679        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2680                false/* because of non-split user */);
2681        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2682                false/* because of non-split user */);
2683    }
2684
2685    public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2686            throws Exception {
2687        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2688        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2689        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2690                DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2691        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2692                DevicePolicyManager.CODE_OK);
2693        assertCheckProvisioningPreCondition(
2694                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2695                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2696        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2697                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2698    }
2699
2700    public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2701        setup_nonSplitUser_withDo_primaryUser();
2702        mContext.packageName = admin1.getPackageName();
2703        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2704
2705        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2706                DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2707        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2708
2709        // COMP mode is allowed.
2710        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2711                DevicePolicyManager.CODE_OK);
2712        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2713
2714        // And other DPCs can also provision a managed profile (DO + BYOD case).
2715        assertCheckProvisioningPreCondition(
2716                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2717                DpmMockContext.ANOTHER_PACKAGE_NAME,
2718                DevicePolicyManager.CODE_OK);
2719        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2720                DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2721    }
2722
2723    public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2724        setup_nonSplitUser_withDo_primaryUser();
2725        mContext.packageName = admin1.getPackageName();
2726        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2727        // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2728        // other packages should be forbidden.
2729        when(mContext.userManager.hasUserRestriction(
2730                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2731                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2732                .thenReturn(true);
2733        when(mContext.userManager.getUserRestrictionSource(
2734                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2735                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2736                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2737        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2738                DevicePolicyManager.CODE_OK);
2739        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2740        assertCheckProvisioningPreCondition(
2741                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2742                DpmMockContext.ANOTHER_PACKAGE_NAME,
2743                DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2744        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2745                DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2746    }
2747
2748    public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2749            throws Exception {
2750        setup_nonSplitUser_withDo_primaryUser();
2751        mContext.packageName = admin1.getPackageName();
2752        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2753        // The DO should not be allowed to initiate provisioning if the restriction is set by
2754        // another entity.
2755        when(mContext.userManager.hasUserRestriction(
2756                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2757                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2758                .thenReturn(true);
2759        when(mContext.userManager.getUserRestrictionSource(
2760                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2761                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2762                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2763        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2764                DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2765        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2766
2767        assertCheckProvisioningPreCondition(
2768                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2769                DpmMockContext.ANOTHER_PACKAGE_NAME,
2770                DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2771        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2772                DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2773    }
2774
2775    public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2776        setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2777        mContext.packageName = admin1.getPackageName();
2778        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2779
2780        // We can delete the managed profile to create a new one, so provisioning is allowed.
2781        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2782                DevicePolicyManager.CODE_OK);
2783        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2784        assertCheckProvisioningPreCondition(
2785                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2786                DpmMockContext.ANOTHER_PACKAGE_NAME,
2787                DevicePolicyManager.CODE_OK);
2788        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2789                DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2790    }
2791
2792    public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2793            throws Exception {
2794        setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2795        mContext.packageName = admin1.getPackageName();
2796        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2797        when(mContext.userManager.hasUserRestriction(
2798                eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2799                eq(UserHandle.SYSTEM)))
2800                .thenReturn(true);
2801        when(mContext.userManager.getUserRestrictionSource(
2802                eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2803                eq(UserHandle.SYSTEM)))
2804                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2805
2806        // We can't remove the profile to create a new one.
2807        assertCheckProvisioningPreCondition(
2808                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2809                DpmMockContext.ANOTHER_PACKAGE_NAME,
2810                DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2811        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2812                DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2813
2814        // But the device owner can still do it because it has set the restriction itself.
2815        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2816                DevicePolicyManager.CODE_OK);
2817        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2818    }
2819
2820    private void setup_splitUser_firstBoot_systemUser() throws Exception {
2821        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2822                .thenReturn(true);
2823        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2824        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2825                .thenReturn(false);
2826        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2827
2828        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2829    }
2830
2831    public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2832        setup_splitUser_firstBoot_systemUser();
2833        mContext.packageName = admin1.getPackageName();
2834        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2835        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2836        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2837                false /* because canAddMoreManagedProfiles returns false */);
2838        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2839                true);
2840        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2841                false/* because calling uid is system user */);
2842    }
2843
2844    public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2845            throws Exception {
2846        setup_splitUser_firstBoot_systemUser();
2847        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2848        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2849                DevicePolicyManager.CODE_OK);
2850        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2851                DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2852        assertCheckProvisioningPreCondition(
2853                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2854                DevicePolicyManager.CODE_OK);
2855        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2856                DevicePolicyManager.CODE_SYSTEM_USER);
2857    }
2858
2859    private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
2860        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2861                .thenReturn(true);
2862        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2863        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2864                .thenReturn(false);
2865        setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2866
2867        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2868    }
2869
2870    public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2871        setup_splitUser_afterDeviceSetup_systemUser();
2872        mContext.packageName = admin1.getPackageName();
2873        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2874        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2875                true/* it's undefined behavior. Can be changed into false in the future */);
2876        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2877                false /* because canAddMoreManagedProfiles returns false */);
2878        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2879                true/* it's undefined behavior. Can be changed into false in the future */);
2880        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2881                false/* because calling uid is system user */);
2882    }
2883
2884    public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2885            throws Exception {
2886        setup_splitUser_afterDeviceSetup_systemUser();
2887        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2888        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2889                DevicePolicyManager.CODE_OK);
2890        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2891                DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2892        assertCheckProvisioningPreCondition(
2893                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2894                DevicePolicyManager.CODE_OK);
2895        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2896                DevicePolicyManager.CODE_SYSTEM_USER);
2897    }
2898
2899    private void setup_splitUser_firstBoot_primaryUser() throws Exception {
2900        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2901                .thenReturn(true);
2902        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2903        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2904                true)).thenReturn(true);
2905        setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2906
2907        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2908    }
2909
2910    public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2911        setup_splitUser_firstBoot_primaryUser();
2912        mContext.packageName = admin1.getPackageName();
2913        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2914        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2915        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2916        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2917                true);
2918        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2919    }
2920
2921    public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
2922            throws Exception {
2923        setup_splitUser_firstBoot_primaryUser();
2924        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2925        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2926                DevicePolicyManager.CODE_OK);
2927        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2928                DevicePolicyManager.CODE_OK);
2929        assertCheckProvisioningPreCondition(
2930                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2931                DevicePolicyManager.CODE_OK);
2932        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2933                DevicePolicyManager.CODE_OK);
2934    }
2935
2936    private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
2937        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2938                .thenReturn(true);
2939        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2940        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2941                true)).thenReturn(true);
2942        setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2943
2944        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2945    }
2946
2947    public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2948            throws Exception {
2949        setup_splitUser_afterDeviceSetup_primaryUser();
2950        mContext.packageName = admin1.getPackageName();
2951        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2952        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2953                true/* it's undefined behavior. Can be changed into false in the future */);
2954        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2955        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2956                true/* it's undefined behavior. Can be changed into false in the future */);
2957        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2958                false/* because user setup completed */);
2959    }
2960
2961    public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
2962            throws Exception {
2963        setup_splitUser_afterDeviceSetup_primaryUser();
2964        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2965        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2966                DevicePolicyManager.CODE_OK);
2967        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2968                DevicePolicyManager.CODE_OK);
2969        assertCheckProvisioningPreCondition(
2970                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2971                DevicePolicyManager.CODE_OK);
2972        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2973                DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2974    }
2975
2976    private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
2977        setDeviceOwner();
2978
2979        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2980                .thenReturn(true);
2981        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2982        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2983                .thenReturn(false);
2984        setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2985
2986        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2987    }
2988
2989    public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2990            throws Exception {
2991        setup_provisionManagedProfileWithDeviceOwner_systemUser();
2992        mContext.packageName = admin1.getPackageName();
2993        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2994        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2995                false /* can't provision managed profile on system user */);
2996    }
2997
2998    public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
2999            throws Exception {
3000        setup_provisionManagedProfileWithDeviceOwner_systemUser();
3001        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3002        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3003                DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3004    }
3005
3006    private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
3007        setDeviceOwner();
3008
3009        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3010                .thenReturn(true);
3011        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3012        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3013                true)).thenReturn(true);
3014        setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3015
3016        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3017    }
3018
3019    public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3020            throws Exception {
3021        setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3022        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3023        mContext.packageName = admin1.getPackageName();
3024        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3025    }
3026
3027    public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
3028            throws Exception {
3029        setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3030        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3031
3032        // COMP mode is allowed.
3033        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3034                DevicePolicyManager.CODE_OK);
3035    }
3036
3037    private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
3038        setDeviceOwner();
3039
3040        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3041                .thenReturn(true);
3042        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3043        when(mContext.userManager.hasUserRestriction(
3044                eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3045                eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
3046                .thenReturn(true);
3047        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3048                false /* we can't remove a managed profile */)).thenReturn(false);
3049        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3050                true)).thenReturn(true);
3051        setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3052
3053        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3054    }
3055
3056    public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3057            throws Exception {
3058        setup_provisionManagedProfileCantRemoveUser_primaryUser();
3059        mContext.packageName = admin1.getPackageName();
3060        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3061        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3062    }
3063
3064    public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3065            throws Exception {
3066        setup_provisionManagedProfileCantRemoveUser_primaryUser();
3067        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3068        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3069                DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3070    }
3071
3072    public void testCheckProvisioningPreCondition_permission() {
3073        // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3074        try {
3075            dpm.checkProvisioningPreCondition(
3076                    DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
3077            fail("Didn't throw SecurityException");
3078        } catch (SecurityException expected) {
3079        }
3080    }
3081
3082    public void testForceUpdateUserSetupComplete_permission() {
3083        // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3084        try {
3085            dpm.forceUpdateUserSetupComplete();
3086            fail("Didn't throw SecurityException");
3087        } catch (SecurityException expected) {
3088        }
3089    }
3090
3091    public void testForceUpdateUserSetupComplete_systemUser() {
3092        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3093        // GIVEN calling from user 20
3094        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3095        try {
3096            dpm.forceUpdateUserSetupComplete();
3097            fail("Didn't throw SecurityException");
3098        } catch (SecurityException expected) {
3099        }
3100    }
3101
3102    public void testForceUpdateUserSetupComplete_userbuild() {
3103        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3104        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3105
3106        final int userId = UserHandle.USER_SYSTEM;
3107        // GIVEN userComplete is false in SettingsProvider
3108        setUserSetupCompleteForUser(false, userId);
3109
3110        // GIVEN userComplete is true in DPM
3111        DevicePolicyManagerService.DevicePolicyData userData =
3112                new DevicePolicyManagerService.DevicePolicyData(userId);
3113        userData.mUserSetupComplete = true;
3114        dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3115
3116        // GIVEN it's user build
3117        mContext.buildMock.isDebuggable = false;
3118
3119        assertTrue(dpms.hasUserSetupCompleted());
3120
3121        dpm.forceUpdateUserSetupComplete();
3122
3123        // THEN the state in dpms is not changed
3124        assertTrue(dpms.hasUserSetupCompleted());
3125    }
3126
3127    public void testForceUpdateUserSetupComplete_userDebugbuild() {
3128        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3129        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3130
3131        final int userId = UserHandle.USER_SYSTEM;
3132        // GIVEN userComplete is false in SettingsProvider
3133        setUserSetupCompleteForUser(false, userId);
3134
3135        // GIVEN userComplete is true in DPM
3136        DevicePolicyManagerService.DevicePolicyData userData =
3137                new DevicePolicyManagerService.DevicePolicyData(userId);
3138        userData.mUserSetupComplete = true;
3139        dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3140
3141        // GIVEN it's userdebug build
3142        mContext.buildMock.isDebuggable = true;
3143
3144        assertTrue(dpms.hasUserSetupCompleted());
3145
3146        dpm.forceUpdateUserSetupComplete();
3147
3148        // THEN the state in dpms is not changed
3149        assertFalse(dpms.hasUserSetupCompleted());
3150    }
3151
3152    private void clearDeviceOwner() throws Exception {
3153        final long ident = mContext.binder.clearCallingIdentity();
3154        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3155        doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3156                .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3157        dpm.clearDeviceOwnerApp(admin1.getPackageName());
3158        mContext.binder.restoreCallingIdentity(ident);
3159    }
3160
3161    public void testGetLastSecurityLogRetrievalTime() throws Exception {
3162        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3163        setupDeviceOwner();
3164
3165        // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3166        // feature is disabled because there are non-affiliated secondary users.
3167        mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3168        when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3169                .thenReturn(true);
3170
3171        // No logs were retrieved so far.
3172        assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
3173
3174        // Enabling logging should not change the timestamp.
3175        dpm.setSecurityLoggingEnabled(admin1, true);
3176        verify(mContext.settings)
3177                .securityLogSetLoggingEnabledProperty(true);
3178        when(mContext.settings.securityLogGetLoggingEnabledProperty())
3179                .thenReturn(true);
3180        assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
3181
3182        // Retrieving the logs should update the timestamp.
3183        final long beforeRetrieval = System.currentTimeMillis();
3184        dpm.retrieveSecurityLogs(admin1);
3185        final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
3186        final long afterRetrieval = System.currentTimeMillis();
3187        assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3188        assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3189
3190        // Retrieving the pre-boot logs should update the timestamp.
3191        Thread.sleep(2);
3192        dpm.retrievePreRebootSecurityLogs(admin1);
3193        final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
3194        assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3195
3196        // Checking the timestamp again should not change it.
3197        Thread.sleep(2);
3198        assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3199
3200        // Retrieving the logs again should update the timestamp.
3201        dpm.retrieveSecurityLogs(admin1);
3202        final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
3203        assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3204
3205        // Disabling logging should not change the timestamp.
3206        Thread.sleep(2);
3207        dpm.setSecurityLoggingEnabled(admin1, false);
3208        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3209
3210        // Restarting the DPMS should not lose the timestamp.
3211        initializeDpms();
3212        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3213
3214        // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3215        mContext.binder.callingUid = 1234567;
3216        mContext.callerPermissions.add(permission.MANAGE_USERS);
3217        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3218        mContext.callerPermissions.remove(permission.MANAGE_USERS);
3219
3220        // System can retrieve the timestamp.
3221        mContext.binder.clearCallingIdentity();
3222        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3223
3224        // Removing the device owner should clear the timestamp.
3225        clearDeviceOwner();
3226        assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
3227    }
3228
3229    public void testGetLastBugReportRequestTime() throws Exception {
3230        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3231        setupDeviceOwner();
3232
3233        mContext.packageName = admin1.getPackageName();
3234        mContext.applicationInfo = new ApplicationInfo();
3235        when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3236                .thenReturn(Color.WHITE);
3237        when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3238                anyObject())).thenReturn(Color.WHITE);
3239
3240        // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3241        // feature is disabled because there are non-affiliated secondary users.
3242        mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3243
3244        // No bug reports were requested so far.
3245        assertEquals(-1, dpm.getLastBugReportRequestTime());
3246
3247        // Requesting a bug report should update the timestamp.
3248        final long beforeRequest = System.currentTimeMillis();
3249        dpm.requestBugreport(admin1);
3250        final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
3251        final long afterRequest = System.currentTimeMillis();
3252        assertTrue(bugReportRequestTime >= beforeRequest);
3253        assertTrue(bugReportRequestTime <= afterRequest);
3254
3255        // Checking the timestamp again should not change it.
3256        Thread.sleep(2);
3257        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3258
3259        // Restarting the DPMS should not lose the timestamp.
3260        initializeDpms();
3261        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3262
3263        // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3264        mContext.binder.callingUid = 1234567;
3265        mContext.callerPermissions.add(permission.MANAGE_USERS);
3266        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3267        mContext.callerPermissions.remove(permission.MANAGE_USERS);
3268
3269        // System can retrieve the timestamp.
3270        mContext.binder.clearCallingIdentity();
3271        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3272
3273        // Removing the device owner should clear the timestamp.
3274        clearDeviceOwner();
3275        assertEquals(-1, dpm.getLastBugReportRequestTime());
3276    }
3277
3278    public void testGetLastNetworkLogRetrievalTime() throws Exception {
3279        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3280        setupDeviceOwner();
3281        mContext.packageName = admin1.getPackageName();
3282        mContext.applicationInfo = new ApplicationInfo();
3283        when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3284                .thenReturn(Color.WHITE);
3285        when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3286                anyObject())).thenReturn(Color.WHITE);
3287
3288        // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3289        // feature is disabled because there are non-affiliated secondary users.
3290        mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3291        when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3292                .thenReturn(true);
3293
3294        // No logs were retrieved so far.
3295        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3296
3297        // Attempting to retrieve logs without enabling logging should not change the timestamp.
3298        dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
3299        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3300
3301        // Enabling logging should not change the timestamp.
3302        dpm.setNetworkLoggingEnabled(admin1, true);
3303        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3304
3305        // Retrieving the logs should update the timestamp.
3306        final long beforeRetrieval = System.currentTimeMillis();
3307        dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
3308        final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
3309        final long afterRetrieval = System.currentTimeMillis();
3310        assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3311        assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3312
3313        // Checking the timestamp again should not change it.
3314        Thread.sleep(2);
3315        assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3316
3317        // Retrieving the logs again should update the timestamp.
3318        dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
3319        final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
3320        assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3321
3322        // Disabling logging should not change the timestamp.
3323        Thread.sleep(2);
3324        dpm.setNetworkLoggingEnabled(admin1, false);
3325        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3326
3327        // Restarting the DPMS should not lose the timestamp.
3328        initializeDpms();
3329        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3330
3331        // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3332        mContext.binder.callingUid = 1234567;
3333        mContext.callerPermissions.add(permission.MANAGE_USERS);
3334        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3335        mContext.callerPermissions.remove(permission.MANAGE_USERS);
3336
3337        // System can retrieve the timestamp.
3338        mContext.binder.clearCallingIdentity();
3339        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3340
3341        // Removing the device owner should clear the timestamp.
3342        clearDeviceOwner();
3343        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3344    }
3345
3346    public void testGetBindDeviceAdminTargetUsers() throws Exception {
3347        // Setup device owner.
3348        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3349        setupDeviceOwner();
3350
3351        // Only device owner is setup, the result list should be empty.
3352        List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3353        MoreAsserts.assertEmpty(targetUsers);
3354
3355        // Setup a managed profile managed by the same admin.
3356        final int MANAGED_PROFILE_USER_ID = 15;
3357        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3358        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3359
3360        // Add a secondary user, it should never talk with.
3361        final int ANOTHER_USER_ID = 36;
3362        mContext.addUser(ANOTHER_USER_ID, 0);
3363
3364        // Since the managed profile is not affiliated, they should not be allowed to talk to each
3365        // other.
3366        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3367        MoreAsserts.assertEmpty(targetUsers);
3368
3369        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3370        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3371        MoreAsserts.assertEmpty(targetUsers);
3372
3373        // Setting affiliation ids
3374        final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3375        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3376        dpm.setAffiliationIds(admin1, userAffiliationIds);
3377
3378        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3379        dpm.setAffiliationIds(admin1, userAffiliationIds);
3380
3381        // Calling from device owner admin, the result list should just contain the managed
3382        // profile user id.
3383        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3384        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3385        MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3386
3387        // Calling from managed profile admin, the result list should just contain the system
3388        // user id.
3389        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3390        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3391        MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
3392
3393        // Changing affiliation ids in one
3394        dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3395
3396        // Since the managed profile is not affiliated any more, they should not be allowed to talk
3397        // to each other.
3398        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3399        MoreAsserts.assertEmpty(targetUsers);
3400
3401        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3402        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3403        MoreAsserts.assertEmpty(targetUsers);
3404    }
3405
3406    public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3407        // Setup a device owner.
3408        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3409        setupDeviceOwner();
3410
3411        // Set up a managed profile managed by different package.
3412        final int MANAGED_PROFILE_USER_ID = 15;
3413        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3414        final ComponentName adminDifferentPackage =
3415                new ComponentName("another.package", "whatever.class");
3416        addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3417
3418        // Setting affiliation ids
3419        final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3420        dpm.setAffiliationIds(admin1, userAffiliationIds);
3421
3422        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3423        dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3424
3425        // Calling from device owner admin, we should get zero bind device admin target users as
3426        // their packages are different.
3427        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3428        List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3429        MoreAsserts.assertEmpty(targetUsers);
3430
3431        // Calling from managed profile admin, we should still get zero target users for the same
3432        // reason.
3433        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3434        targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3435        MoreAsserts.assertEmpty(targetUsers);
3436    }
3437
3438    public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3439        // Setup a device owner.
3440        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3441        setupDeviceOwner();
3442        // Lock task packages are updated when loading user data.
3443        verify(mContext.iactivityManager)
3444                .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3445
3446        // Set up a managed profile managed by different package (package name shouldn't matter)
3447        final int MANAGED_PROFILE_USER_ID = 15;
3448        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3449        final ComponentName adminDifferentPackage =
3450                new ComponentName("another.package", "whatever.class");
3451        addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3452        verify(mContext.iactivityManager)
3453                .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3454
3455        // The DO can still set lock task packages
3456        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3457        final String[] doPackages = {"doPackage1", "doPackage2"};
3458        dpm.setLockTaskPackages(admin1, doPackages);
3459        MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3460        assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3461        assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3462        verify(mContext.iactivityManager)
3463                .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3464
3465        // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3466        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3467        final String[] poPackages = {"poPackage1", "poPackage2"};
3468        try {
3469            dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3470            fail("Didn't throw expected security exception.");
3471        } catch (SecurityException expected) {
3472        }
3473        try {
3474            dpm.getLockTaskPackages(adminDifferentPackage);
3475            fail("Didn't throw expected security exception.");
3476        } catch (SecurityException expected) {
3477        }
3478        assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3479
3480        // Setting same affiliation ids
3481        final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3482        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3483        dpm.setAffiliationIds(admin1, userAffiliationIds);
3484
3485        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3486        dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3487
3488        // Now the managed profile can set lock task packages.
3489        dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3490        MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3491        assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3492        assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3493        verify(mContext.iactivityManager)
3494                .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3495
3496        // Unaffiliate the profile, lock task mode no longer available on the profile.
3497        dpm.setAffiliationIds(adminDifferentPackage, Collections.<String>emptyList());
3498        assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3499        // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3500        verify(mContext.iactivityManager, times(2))
3501                .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3502
3503        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3504        assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3505    }
3506
3507    public void testIsDeviceManaged() throws Exception {
3508        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3509        setupDeviceOwner();
3510
3511        // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3512        // find out that the device has a device owner.
3513        assertTrue(dpm.isDeviceManaged());
3514        mContext.binder.callingUid = 1234567;
3515        mContext.callerPermissions.add(permission.MANAGE_USERS);
3516        assertTrue(dpm.isDeviceManaged());
3517        mContext.callerPermissions.remove(permission.MANAGE_USERS);
3518        mContext.binder.clearCallingIdentity();
3519        assertTrue(dpm.isDeviceManaged());
3520
3521        clearDeviceOwner();
3522
3523        // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3524        // not have a device owner.
3525        mContext.binder.callingUid = 1234567;
3526        mContext.callerPermissions.add(permission.MANAGE_USERS);
3527        assertFalse(dpm.isDeviceManaged());
3528        mContext.callerPermissions.remove(permission.MANAGE_USERS);
3529        mContext.binder.clearCallingIdentity();
3530        assertFalse(dpm.isDeviceManaged());
3531    }
3532
3533    public void testDeviceOwnerOrganizationName() throws Exception {
3534        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3535        setupDeviceOwner();
3536
3537        dpm.setOrganizationName(admin1, "organization");
3538
3539        // Device owner can retrieve organization managing the device.
3540        assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3541
3542        // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3543        mContext.binder.callingUid = 1234567;
3544        mContext.callerPermissions.add(permission.MANAGE_USERS);
3545        assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3546        mContext.callerPermissions.remove(permission.MANAGE_USERS);
3547
3548        // System can retrieve organization managing the device.
3549        mContext.binder.clearCallingIdentity();
3550        assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3551
3552        // Removing the device owner clears the organization managing the device.
3553        clearDeviceOwner();
3554        assertNull(dpm.getDeviceOwnerOrganizationName());
3555    }
3556
3557    public void testWipeDataManagedProfile() throws Exception {
3558        final int MANAGED_PROFILE_USER_ID = 15;
3559        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3560        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3561        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3562
3563        // Even if the caller is the managed profile, the current user is the user 0
3564        when(mContext.iactivityManager.getCurrentUser())
3565                .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3566
3567        dpm.wipeData(0);
3568        verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3569                MANAGED_PROFILE_USER_ID);
3570    }
3571
3572    public void testWipeDataManagedProfileDisallowed() throws Exception {
3573        final int MANAGED_PROFILE_USER_ID = 15;
3574        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3575        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3576
3577        // Even if the caller is the managed profile, the current user is the user 0
3578        when(mContext.iactivityManager.getCurrentUser())
3579                .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3580
3581        when(mContext.userManager.getUserRestrictionSource(
3582                UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3583                UserHandle.of(MANAGED_PROFILE_USER_ID)))
3584                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3585        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3586        try {
3587            // The PO is not allowed to remove the profile if the user restriction was set on the
3588            // profile by the system
3589            dpm.wipeData(0);
3590            fail("SecurityException not thrown");
3591        } catch (SecurityException expected) {
3592        }
3593    }
3594
3595    public void testWipeDataDeviceOwner() throws Exception {
3596        setDeviceOwner();
3597        when(mContext.userManager.getUserRestrictionSource(
3598                UserManager.DISALLOW_FACTORY_RESET,
3599                UserHandle.SYSTEM))
3600                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3601
3602        dpm.wipeData(0);
3603        verify(mContext.recoverySystem).rebootWipeUserData(
3604                /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3605    }
3606
3607    public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3608        setDeviceOwner();
3609        when(mContext.userManager.getUserRestrictionSource(
3610                UserManager.DISALLOW_FACTORY_RESET,
3611                UserHandle.SYSTEM))
3612                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3613        try {
3614            // The DO is not allowed to wipe the device if the user restriction was set
3615            // by the system
3616            dpm.wipeData(0);
3617            fail("SecurityException not thrown");
3618        } catch (SecurityException expected) {
3619        }
3620    }
3621
3622    public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3623        final int MANAGED_PROFILE_USER_ID = 15;
3624        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3625        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3626
3627        // Even if the caller is the managed profile, the current user is the user 0
3628        when(mContext.iactivityManager.getCurrentUser())
3629                .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3630
3631        when(mContext.userManager.getUserRestrictionSource(
3632                UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3633                UserHandle.of(MANAGED_PROFILE_USER_ID)))
3634                .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3635
3636        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3637        dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3638
3639        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3640        mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3641        // Failed password attempts on the parent user are taken into account, as there isn't a
3642        // separate work challenge.
3643        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3644        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3645        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3646
3647        // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3648        // both the user restriction and the policy were set by the PO.
3649        verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3650                MANAGED_PROFILE_USER_ID);
3651        verifyZeroInteractions(mContext.recoverySystem);
3652    }
3653
3654    public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3655            throws Exception {
3656        final int MANAGED_PROFILE_USER_ID = 15;
3657        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3658        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3659
3660        // Even if the caller is the managed profile, the current user is the user 0
3661        when(mContext.iactivityManager.getCurrentUser())
3662                .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3663
3664        when(mContext.userManager.getUserRestrictionSource(
3665                UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3666                UserHandle.of(MANAGED_PROFILE_USER_ID)))
3667                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3668
3669        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3670        dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3671
3672        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3673        mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3674        // Failed password attempts on the parent user are taken into account, as there isn't a
3675        // separate work challenge.
3676        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3677        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3678        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3679
3680        // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3681        // not wiped.
3682        verify(mContext.userManagerInternal, never())
3683                .removeUserEvenWhenDisallowed(anyInt());
3684        verifyZeroInteractions(mContext.recoverySystem);
3685    }
3686
3687    public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3688        setDeviceOwner();
3689        when(mContext.userManager.getUserRestrictionSource(
3690                UserManager.DISALLOW_FACTORY_RESET,
3691                UserHandle.SYSTEM))
3692                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3693
3694        dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3695
3696        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3697        mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3698        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3699        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3700        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3701
3702        // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3703        // user restriction and the policy were set by the DO.
3704        verify(mContext.recoverySystem).rebootWipeUserData(
3705                /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3706    }
3707
3708    public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3709        setDeviceOwner();
3710        when(mContext.userManager.getUserRestrictionSource(
3711                UserManager.DISALLOW_FACTORY_RESET,
3712                UserHandle.SYSTEM))
3713                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3714
3715        dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3716
3717        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3718        mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3719        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3720        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3721        dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3722
3723        // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3724        verifyZeroInteractions(mContext.recoverySystem);
3725        verify(mContext.userManagerInternal, never())
3726                .removeUserEvenWhenDisallowed(anyInt());
3727    }
3728
3729    public void testGetPermissionGrantState() throws Exception {
3730        final String permission = "some.permission";
3731        final String app1 = "com.example.app1";
3732        final String app2 = "com.example.app2";
3733
3734        when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3735                .thenReturn(PackageManager.PERMISSION_GRANTED);
3736        doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3737                .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3738        when(mContext.packageManager.getPermissionFlags(permission, app1,
3739                UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3740                .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3741        when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3742                .thenReturn(PackageManager.PERMISSION_DENIED);
3743        doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3744                UserHandle.SYSTEM);
3745        when(mContext.packageManager.getPermissionFlags(permission, app2,
3746                UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3747
3748        // System can retrieve permission grant state.
3749        mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3750        mContext.packageName = "com.example.system";
3751        assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3752                dpm.getPermissionGrantState(null, app1, permission));
3753        assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3754                dpm.getPermissionGrantState(null, app2, permission));
3755
3756        // A regular app cannot retrieve permission grant state.
3757        mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3758        mContext.packageName = app1;
3759        try {
3760            dpm.getPermissionGrantState(null, app1, permission);
3761            fail("Didn't throw SecurityException");
3762        } catch (SecurityException expected) {
3763        }
3764
3765        // Profile owner can retrieve permission grant state.
3766        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3767        mContext.packageName = admin1.getPackageName();
3768        setAsProfileOwner(admin1);
3769        assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3770                dpm.getPermissionGrantState(admin1, app1, permission));
3771        assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3772                dpm.getPermissionGrantState(admin1, app2, permission));
3773    }
3774
3775    public void testResetPasswordWithToken() throws Exception {
3776        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3777        setupDeviceOwner();
3778        // test token validation
3779        try {
3780            dpm.setResetPasswordToken(admin1, new byte[31]);
3781            fail("should not have accepted tokens too short");
3782        } catch (IllegalArgumentException expected) {
3783        }
3784        // test adding a token
3785        final byte[] token = new byte[32];
3786        final long handle = 123456;
3787        final String password = "password";
3788        when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3789            .thenReturn(handle);
3790        assertTrue(dpm.setResetPasswordToken(admin1, token));
3791
3792        // test password activation
3793        when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3794            .thenReturn(true);
3795        assertTrue(dpm.isResetPasswordTokenActive(admin1));
3796
3797        // test reset password with token
3798        when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3799                eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3800                eq(UserHandle.USER_SYSTEM)))
3801                .thenReturn(true);
3802        assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3803
3804        // test removing a token
3805        when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3806                .thenReturn(true);
3807        assertTrue(dpm.clearResetPasswordToken(admin1));
3808    }
3809
3810    public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3811        final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3812        final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3813        final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3814        final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3815                DpmMockContext.SYSTEM_UID);
3816        final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3817                DpmMockContext.SYSTEM_UID);
3818
3819        // Set up a device owner.
3820        mContext.binder.callingUid = deviceOwnerUid;
3821        setupDeviceOwner();
3822
3823        // First and second user set IMEs manually.
3824        mContext.binder.callingUid = firstUserSystemUid;
3825        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3826        mContext.binder.callingUid = secondUserSystemUid;
3827        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3828
3829        // Device owner changes IME for first user.
3830        mContext.binder.callingUid = deviceOwnerUid;
3831        when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
3832                .thenReturn("ime1");
3833        dpm.setSecureSetting(admin1, currentIme, "ime2");
3834        verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
3835                UserHandle.USER_SYSTEM);
3836        reset(mContext.settings);
3837        dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3838        mContext.binder.callingUid = firstUserSystemUid;
3839        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3840        mContext.binder.callingUid = secondUserSystemUid;
3841        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3842
3843        // Second user changes IME manually.
3844        dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3845        mContext.binder.callingUid = firstUserSystemUid;
3846        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3847        mContext.binder.callingUid = secondUserSystemUid;
3848        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3849
3850        // First user changes IME manually.
3851        dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3852        mContext.binder.callingUid = firstUserSystemUid;
3853        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3854        mContext.binder.callingUid = secondUserSystemUid;
3855        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3856
3857        // Device owner changes IME for first user again.
3858        mContext.binder.callingUid = deviceOwnerUid;
3859        when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
3860                .thenReturn("ime2");
3861        dpm.setSecureSetting(admin1, currentIme, "ime3");
3862        verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
3863                UserHandle.USER_SYSTEM);
3864        dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3865        mContext.binder.callingUid = firstUserSystemUid;
3866        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3867        mContext.binder.callingUid = secondUserSystemUid;
3868        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3869
3870        // Restarting the DPMS should not lose information.
3871        initializeDpms();
3872        mContext.binder.callingUid = firstUserSystemUid;
3873        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3874        mContext.binder.callingUid = secondUserSystemUid;
3875        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3876
3877        // Device owner can find out whether it set the current IME itself.
3878        mContext.binder.callingUid = deviceOwnerUid;
3879        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3880
3881        // Removing the device owner should clear the information that it set the current IME.
3882        clearDeviceOwner();
3883        mContext.binder.callingUid = firstUserSystemUid;
3884        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3885        mContext.binder.callingUid = secondUserSystemUid;
3886        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3887    }
3888
3889    public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3890        final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3891        final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3892        final int profileOwnerUid = DpmMockContext.CALLER_UID;
3893        final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3894                DpmMockContext.SYSTEM_UID);
3895        final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3896                DpmMockContext.SYSTEM_UID);
3897
3898        // Set up a profile owner.
3899        mContext.binder.callingUid = profileOwnerUid;
3900        setupProfileOwner();
3901
3902        // First and second user set IMEs manually.
3903        mContext.binder.callingUid = firstUserSystemUid;
3904        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3905        mContext.binder.callingUid = secondUserSystemUid;
3906        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3907
3908        // Profile owner changes IME for second user.
3909        mContext.binder.callingUid = profileOwnerUid;
3910        when(mContext.settings.settingsSecureGetStringForUser(currentIme,
3911                DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
3912        dpm.setSecureSetting(admin1, currentIme, "ime2");
3913        verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
3914                DpmMockContext.CALLER_USER_HANDLE);
3915        reset(mContext.settings);
3916        dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3917        mContext.binder.callingUid = firstUserSystemUid;
3918        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3919        mContext.binder.callingUid = secondUserSystemUid;
3920        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3921
3922        // First user changes IME manually.
3923        dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3924        mContext.binder.callingUid = firstUserSystemUid;
3925        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3926        mContext.binder.callingUid = secondUserSystemUid;
3927        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3928
3929        // Second user changes IME manually.
3930        dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3931        mContext.binder.callingUid = firstUserSystemUid;
3932        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3933        mContext.binder.callingUid = secondUserSystemUid;
3934        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3935
3936        // Profile owner changes IME for second user again.
3937        mContext.binder.callingUid = profileOwnerUid;
3938        when(mContext.settings.settingsSecureGetStringForUser(currentIme,
3939                DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
3940        dpm.setSecureSetting(admin1, currentIme, "ime3");
3941        verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
3942                DpmMockContext.CALLER_USER_HANDLE);
3943        dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3944        mContext.binder.callingUid = firstUserSystemUid;
3945        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3946        mContext.binder.callingUid = secondUserSystemUid;
3947        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3948
3949        // Restarting the DPMS should not lose information.
3950        initializeDpms();
3951        mContext.binder.callingUid = firstUserSystemUid;
3952        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3953        mContext.binder.callingUid = secondUserSystemUid;
3954        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3955
3956        // Profile owner can find out whether it set the current IME itself.
3957        mContext.binder.callingUid = profileOwnerUid;
3958        assertTrue(dpm.isCurrentInputMethodSetByOwner());
3959
3960        // Removing the profile owner should clear the information that it set the current IME.
3961        dpm.clearProfileOwner(admin1);
3962        mContext.binder.callingUid = firstUserSystemUid;
3963        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3964        mContext.binder.callingUid = secondUserSystemUid;
3965        assertFalse(dpm.isCurrentInputMethodSetByOwner());
3966    }
3967
3968    public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
3969        setDeviceOwner();
3970
3971        mContext.packageName = admin1.getPackageName();
3972        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3973        verifyCanGetOwnerInstalledCaCerts(admin1);
3974    }
3975
3976    public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
3977        setAsProfileOwner(admin1);
3978
3979        mContext.packageName = admin1.getPackageName();
3980        verifyCanGetOwnerInstalledCaCerts(admin1);
3981        verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1);
3982    }
3983
3984    public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
3985        setAsProfileOwner(admin1);
3986
3987        final String delegate = "com.example.delegate";
3988        final int delegateUid = setupPackageInPackageManager(delegate, 20988);
3989        dpm.setCertInstallerPackage(admin1, delegate);
3990
3991        mContext.packageName = delegate;
3992        mContext.binder.callingUid = delegateUid;
3993        verifyCanGetOwnerInstalledCaCerts(null);
3994        verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null);
3995    }
3996
3997    private void verifyCanGetOwnerInstalledCaCerts(ComponentName caller) throws Exception {
3998        final UserHandle user = UserHandle.getUserHandleForUid(mContext.binder.callingUid);
3999        final int ownerUid = user.equals(UserHandle.SYSTEM) ?
4000                DpmMockContext.CALLER_SYSTEM_USER_UID : DpmMockContext.CALLER_UID;
4001
4002        mContext.applicationInfo = new ApplicationInfo();
4003        mContext.userContexts.put(user, mContext);
4004        when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4005
4006        // Install a CA cert.
4007        final String alias = "cert";
4008        final byte[] caCert = TEST_CA.getBytes();
4009        when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4010                .thenReturn(alias);
4011        assertTrue(dpm.installCaCert(caller, caCert));
4012        when(mContext.keyChainConnection.getService().getUserCaAliases())
4013                .thenReturn(asSlice(new String[] {alias}));
4014        mContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED));
4015        flushTasks();
4016
4017        // Device Owner / Profile Owner can find out which CA certs were installed by itself.
4018        final String packageName = mContext.packageName;
4019        mContext.packageName = admin1.getPackageName();
4020        final long callerIdentity = mContext.binder.clearCallingIdentity();
4021        mContext.binder.callingUid = ownerUid;
4022        List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(user);
4023        assertNotNull(ownerInstalledCaCerts);
4024        assertEquals(1, ownerInstalledCaCerts.size());
4025        assertTrue(ownerInstalledCaCerts.contains(alias));
4026
4027        // Restarting the DPMS should not lose information.
4028        initializeDpms();
4029        assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(user));
4030
4031        // System can find out which CA certs were installed by the Device Owner / Profile Owner.
4032        mContext.packageName = "com.android.frameworks.servicestests";
4033        mContext.binder.clearCallingIdentity();
4034        assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(user));
4035
4036        // Remove the CA cert.
4037        mContext.packageName = packageName;
4038        mContext.binder.restoreCallingIdentity(callerIdentity);
4039        reset(mContext.keyChainConnection.getService());
4040        mContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED));
4041        flushTasks();
4042
4043        // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4044        // Owner.
4045        mContext.packageName = admin1.getPackageName();
4046        mContext.binder.callingUid = ownerUid;
4047        ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(user);
4048        assertNotNull(ownerInstalledCaCerts);
4049        assertTrue(ownerInstalledCaCerts.isEmpty());
4050
4051        mContext.packageName = packageName;
4052        mContext.binder.restoreCallingIdentity(callerIdentity);
4053    }
4054
4055    private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(ComponentName caller)
4056            throws Exception {
4057        final UserHandle user = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4058
4059        mContext.applicationInfo = new ApplicationInfo();
4060        mContext.userContexts.put(user, mContext);
4061        when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4062
4063        // Install a CA cert.
4064        final String alias = "cert";
4065        final byte[] caCert = TEST_CA.getBytes();
4066        when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4067                .thenReturn(alias);
4068        assertTrue(dpm.installCaCert(caller, caCert));
4069        when(mContext.keyChainConnection.getService().getUserCaAliases())
4070                .thenReturn(asSlice(new String[] {alias}));
4071        mContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED));
4072        flushTasks();
4073
4074        // Removing the Profile Owner should clear the information which CA certs were installed
4075        // by it.
4076        mContext.packageName = admin1.getPackageName();
4077        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4078        dpm.clearProfileOwner(admin1);
4079        mContext.packageName = "com.android.frameworks.servicestests";
4080        mContext.binder.clearCallingIdentity();
4081        final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(user);
4082        assertNotNull(ownerInstalledCaCerts);
4083        assertTrue(ownerInstalledCaCerts.isEmpty());
4084    }
4085
4086    private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
4087        when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
4088                userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4089        dpms.notifyChangeToContentObserver(
4090                Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4091    }
4092
4093    private void assertProvisioningAllowed(String action, boolean expected) {
4094        assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4095                dpm.isProvisioningAllowed(action));
4096    }
4097
4098    private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4099            int uid) {
4100        String previousPackageName = mContext.packageName;
4101        int previousUid = mMockContext.binder.callingUid;
4102
4103        // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4104        mContext.packageName = packageName;
4105        mMockContext.binder.callingUid = uid;
4106        assertProvisioningAllowed(action, expected);
4107
4108        // Set the previous package name / calling uid to go back to the initial state.
4109        mContext.packageName = previousPackageName;
4110        mMockContext.binder.callingUid = previousUid;
4111    }
4112
4113    private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
4114        assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4115    }
4116
4117    private void assertCheckProvisioningPreCondition(
4118            String action, String packageName, int provisioningCondition) {
4119        assertEquals("checkProvisioningPreCondition("
4120                        + action + ", " + packageName + ") returning unexpected result",
4121                provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
4122    }
4123
4124    /**
4125     * Setup a managed profile with the specified admin and its uid.
4126     * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4127     * @param adminUid uid of the admin package.
4128     * @param copyFromAdmin package information for {@code admin} will be built based on this
4129     *     component's information.
4130     */
4131    private void addManagedProfile(
4132            ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4133        final int userId = UserHandle.getUserId(adminUid);
4134        mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
4135        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4136        setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4137        dpm.setActiveAdmin(admin, false, userId);
4138        assertTrue(dpm.setProfileOwner(admin, null, userId));
4139        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4140    }
4141
4142    /**
4143     * Convert String[] to StringParceledListSlice.
4144     */
4145    private static StringParceledListSlice asSlice(String[] s) {
4146        return new StringParceledListSlice(Arrays.asList(s));
4147    }
4148
4149    private void flushTasks() throws Exception {
4150        Boolean tasksFlushed[] = new Boolean[] {false};
4151        final Runnable tasksFlushedNotifier = () -> {
4152            synchronized (tasksFlushed) {
4153                tasksFlushed[0] = true;
4154                tasksFlushed.notify();
4155            }
4156        };
4157
4158        // Flush main thread handler.
4159        dpms.mHandler.post(tasksFlushedNotifier);
4160        synchronized (tasksFlushed) {
4161            if (!tasksFlushed[0]) {
4162                tasksFlushed.wait();
4163            }
4164        }
4165
4166        // Flush background thread handler.
4167        tasksFlushed[0] = false;
4168        dpms.mBackgroundHandler.post(tasksFlushedNotifier);
4169        synchronized (tasksFlushed) {
4170            if (!tasksFlushed[0]) {
4171                tasksFlushed.wait();
4172            }
4173        }
4174    }
4175}
4176