DevicePolicyManagerTest.java revision 01576869a3f46923d1d893866677e3bf9a00fc2b
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 android.Manifest.permission;
19import android.app.Activity;
20import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
23import android.content.BroadcastReceiver;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
30import android.content.pm.PackageManager;
31import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
34import android.content.pm.UserInfo;
35import android.net.wifi.WifiInfo;
36import android.os.Build.VERSION_CODES;
37import android.os.Bundle;
38import android.os.IBinder;
39import android.os.Process;
40import android.os.UserHandle;
41import android.os.UserManager;
42import android.provider.Settings;
43import android.telephony.TelephonyManager;
44import android.test.MoreAsserts;
45import android.test.suitebuilder.annotation.SmallTest;
46import android.util.ArraySet;
47import android.util.Pair;
48
49import com.android.internal.R;
50import com.android.server.LocalServices;
51import com.android.server.SystemService;
52import com.android.server.pm.UserRestrictionsUtils;
53
54import org.mockito.invocation.InvocationOnMock;
55import org.mockito.stubbing.Answer;
56
57import java.util.ArrayList;
58import java.util.Arrays;
59import java.util.Collections;
60import java.util.HashMap;
61import java.util.List;
62import java.util.Map;
63import java.util.Set;
64
65import static org.mockito.Matchers.any;
66import static org.mockito.Matchers.anyInt;
67import static org.mockito.Matchers.anyObject;
68import static org.mockito.Matchers.anyString;
69import static org.mockito.Matchers.eq;
70import static org.mockito.Matchers.isNull;
71import static org.mockito.Mockito.doAnswer;
72import static org.mockito.Mockito.doReturn;
73import static org.mockito.Mockito.reset;
74import static org.mockito.Mockito.times;
75import static org.mockito.Mockito.verify;
76import static org.mockito.Mockito.when;
77
78/**
79 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
80 * You can run them via:
81 m FrameworksServicesTests &&
82 adb install \
83   -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
84 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
85   -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
86
87 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
88 *
89 * , or:
90 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
91 */
92@SmallTest
93public class DevicePolicyManagerTest extends DpmTestBase {
94    private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
95            permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
96            permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
97
98    private DpmMockContext mContext;
99    public DevicePolicyManager dpm;
100    public DevicePolicyManagerServiceTestable dpms;
101
102    @Override
103    protected void setUp() throws Exception {
104        super.setUp();
105
106        mContext = getContext();
107
108        when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
109                .thenReturn(true);
110
111        // By default, pretend all users are running and unlocked.
112        when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
113
114        initializeDpms();
115
116        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
117        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
118        setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
119        setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
120
121        setUpUserManager();
122    }
123
124    private void initializeDpms() {
125        // Need clearCallingIdentity() to pass permission checks.
126        final long ident = mContext.binder.clearCallingIdentity();
127        try {
128            LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
129
130            dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
131
132            dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
133            dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
134
135            dpm = new DevicePolicyManagerTestable(mContext, dpms);
136        } finally {
137            mContext.binder.restoreCallingIdentity(ident);
138        }
139    }
140
141    private void setUpUserManager() {
142        // Emulate UserManager.set/getApplicationRestriction().
143        final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
144
145        // UM.setApplicationRestrictions() will save to appRestrictions.
146        doAnswer(new Answer<Void>() {
147            @Override
148            public Void answer(InvocationOnMock invocation) throws Throwable {
149                String pkg = (String) invocation.getArguments()[0];
150                Bundle bundle = (Bundle) invocation.getArguments()[1];
151                UserHandle user = (UserHandle) invocation.getArguments()[2];
152
153                appRestrictions.put(Pair.create(pkg, user), bundle);
154
155                return null;
156            }
157        }).when(mContext.userManager).setApplicationRestrictions(
158                anyString(), any(Bundle.class), any(UserHandle.class));
159
160        // UM.getApplicationRestrictions() will read from appRestrictions.
161        doAnswer(new Answer<Bundle>() {
162            @Override
163            public Bundle answer(InvocationOnMock invocation) throws Throwable {
164                String pkg = (String) invocation.getArguments()[0];
165                UserHandle user = (UserHandle) invocation.getArguments()[1];
166
167                return appRestrictions.get(Pair.create(pkg, user));
168            }
169        }).when(mContext.userManager).getApplicationRestrictions(
170                anyString(), any(UserHandle.class));
171
172        // Add the first secondary user.
173        mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
174    }
175
176    private void setAsProfileOwner(ComponentName admin) {
177        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
178        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
179
180        // PO needs to be an DA.
181        dpm.setActiveAdmin(admin, /* replace =*/ false);
182
183        // Fire!
184        assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
185
186        // Check
187        assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
188    }
189
190    public void testHasNoFeature() throws Exception {
191        when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
192                .thenReturn(false);
193
194        LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
195        new DevicePolicyManagerServiceTestable(mContext, dataDir);
196
197        // If the device has no DPMS feature, it shouldn't register the local service.
198        assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
199    }
200
201    /**
202     * Caller doesn't have proper permissions.
203     */
204    public void testSetActiveAdmin_SecurityException() {
205        // 1. Failure cases.
206
207        // Caller doesn't have MANAGE_DEVICE_ADMINS.
208        try {
209            dpm.setActiveAdmin(admin1, false);
210            fail("Didn't throw SecurityException");
211        } catch (SecurityException expected) {
212        }
213
214        // Caller has MANAGE_DEVICE_ADMINS, but for different user.
215        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
216        try {
217            dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
218            fail("Didn't throw SecurityException");
219        } catch (SecurityException expected) {
220        }
221    }
222
223    /**
224     * Test for:
225     * {@link DevicePolicyManager#setActiveAdmin}
226     * with replace=false and replace=true
227     * {@link DevicePolicyManager#isAdminActive}
228     * {@link DevicePolicyManager#isAdminActiveAsUser}
229     * {@link DevicePolicyManager#getActiveAdmins}
230     * {@link DevicePolicyManager#getActiveAdminsAsUser}
231     */
232    public void testSetActiveAdmin() throws Exception {
233        // 1. Make sure the caller has proper permissions.
234        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
235
236        // 2. Call the API.
237        dpm.setActiveAdmin(admin1, /* replace =*/ false);
238
239        // 3. Verify internal calls.
240
241        // Check if the boradcast is sent.
242        verify(mContext.spiedContext).sendBroadcastAsUser(
243                MockUtils.checkIntentAction(
244                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
245                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
246        verify(mContext.spiedContext).sendBroadcastAsUser(
247                MockUtils.checkIntentAction(
248                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
249                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
250
251        verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
252                eq(admin1.getPackageName()),
253                eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
254                eq(PackageManager.DONT_KILL_APP),
255                eq(DpmMockContext.CALLER_USER_HANDLE),
256                anyString());
257
258        // TODO Verify other calls too.
259
260        // Make sure it's active admin1.
261        assertTrue(dpm.isAdminActive(admin1));
262        assertFalse(dpm.isAdminActive(admin2));
263        assertFalse(dpm.isAdminActive(admin3));
264
265        // But not admin1 for a different user.
266
267        // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
268        // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
269        mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
270
271        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
272        assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
273
274        mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
275
276        // Next, add one more admin.
277        // Before doing so, update the application info, now it's enabled.
278        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
279                PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
280
281        dpm.setActiveAdmin(admin2, /* replace =*/ false);
282
283        // Now we have two admins.
284        assertTrue(dpm.isAdminActive(admin1));
285        assertTrue(dpm.isAdminActive(admin2));
286        assertFalse(dpm.isAdminActive(admin3));
287
288        // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
289        // again.  (times(1) because it was previously called for admin1)
290        verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
291                eq(admin1.getPackageName()),
292                eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
293                eq(PackageManager.DONT_KILL_APP),
294                eq(DpmMockContext.CALLER_USER_HANDLE),
295                anyString());
296
297        // 4. Add the same admin1 again without replace, which should throw.
298        try {
299            dpm.setActiveAdmin(admin1, /* replace =*/ false);
300            fail("Didn't throw");
301        } catch (IllegalArgumentException expected) {
302        }
303
304        // 5. Add the same admin1 again with replace, which should succeed.
305        dpm.setActiveAdmin(admin1, /* replace =*/ true);
306
307        // TODO make sure it's replaced.
308
309        // 6. Test getActiveAdmins()
310        List<ComponentName> admins = dpm.getActiveAdmins();
311        assertEquals(2, admins.size());
312        assertEquals(admin1, admins.get(0));
313        assertEquals(admin2, admins.get(1));
314
315        // Another user has no admins.
316        mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
317
318        assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
319                dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
320
321        mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
322    }
323
324    public void testSetActiveAdmin_multiUsers() throws Exception {
325
326        final int ANOTHER_USER_ID = 100;
327        final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
328
329        mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
330
331        // Set up pacakge manager for the other user.
332        setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
333
334        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
335
336        dpm.setActiveAdmin(admin1, /* replace =*/ false);
337
338        mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
339        dpm.setActiveAdmin(admin2, /* replace =*/ false);
340
341
342        mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
343        assertTrue(dpm.isAdminActive(admin1));
344        assertFalse(dpm.isAdminActive(admin2));
345
346        mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
347        assertFalse(dpm.isAdminActive(admin1));
348        assertTrue(dpm.isAdminActive(admin2));
349    }
350
351    /**
352     * Test for:
353     * {@link DevicePolicyManager#setActiveAdmin}
354     * with replace=false
355     */
356    public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
357        // 1. Make sure the caller has proper permissions.
358        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
359
360        dpm.setActiveAdmin(admin1, /* replace =*/ false);
361        assertTrue(dpm.isAdminActive(admin1));
362
363        // Add the same admin1 again without replace, which should throw.
364        try {
365            dpm.setActiveAdmin(admin1, /* replace =*/ false);
366            fail("Didn't throw");
367        } catch (IllegalArgumentException expected) {
368        }
369    }
370
371    /**
372     * Test for:
373     * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
374     * BIND_DEVICE_ADMIN.
375     */
376    public void testSetActiveAdmin_permissionCheck() throws Exception {
377        // 1. Make sure the caller has proper permissions.
378        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
379
380        try {
381            dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
382            fail();
383        } catch (IllegalArgumentException expected) {
384            assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
385        }
386        assertFalse(dpm.isAdminActive(adminNoPerm));
387
388        // Change the target API level to MNC.  Now it can be set as DA.
389        setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
390                VERSION_CODES.M);
391        dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
392        assertTrue(dpm.isAdminActive(adminNoPerm));
393
394        // TODO Test the "load from the file" case where DA will still be loaded even without
395        // BIND_DEVICE_ADMIN and target API is N.
396    }
397
398    /**
399     * Test for:
400     * {@link DevicePolicyManager#removeActiveAdmin}
401     */
402    public void testRemoveActiveAdmin_SecurityException() {
403        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
404
405        // Add admin.
406
407        dpm.setActiveAdmin(admin1, /* replace =*/ false);
408
409        assertTrue(dpm.isAdminActive(admin1));
410
411        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
412
413        // Directly call the DPMS method with a different userid, which should fail.
414        try {
415            dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
416            fail("Didn't throw SecurityException");
417        } catch (SecurityException expected) {
418        }
419
420        // Try to remove active admin with a different caller userid should fail too, without
421        // having MANAGE_DEVICE_ADMINS.
422        mContext.callerPermissions.clear();
423
424        // Change the caller, and call into DPMS directly with a different user-id.
425
426        mContext.binder.callingUid = 1234567;
427        try {
428            dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
429            fail("Didn't throw SecurityException");
430        } catch (SecurityException expected) {
431        }
432    }
433
434    /**
435     * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
436     * (because we can't send the remove broadcast).
437     */
438    public void testRemoveActiveAdmin_userNotRunningOrLocked() {
439        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
440
441        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
442
443        // Add admin.
444
445        dpm.setActiveAdmin(admin1, /* replace =*/ false);
446
447        assertTrue(dpm.isAdminActive(admin1));
448
449        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
450
451        // 1. User not unlocked.
452        when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
453                .thenReturn(false);
454        try {
455            dpm.removeActiveAdmin(admin1);
456            fail("Didn't throw IllegalStateException");
457        } catch (IllegalStateException expected) {
458            MoreAsserts.assertContainsRegex(
459                    "User must be running and unlocked", expected.getMessage());
460        }
461
462        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
463
464        // 2. User unlocked.
465        when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
466                .thenReturn(true);
467
468        dpm.removeActiveAdmin(admin1);
469        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
470    }
471
472    /**
473     * Test for:
474     * {@link DevicePolicyManager#removeActiveAdmin}
475     */
476    public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
477        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
478
479        // Add admin1.
480
481        dpm.setActiveAdmin(admin1, /* replace =*/ false);
482
483        assertTrue(dpm.isAdminActive(admin1));
484        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
485
486        // Different user, but should work, because caller has proper permissions.
487        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
488
489        // Change the caller, and call into DPMS directly with a different user-id.
490        mContext.binder.callingUid = 1234567;
491
492        dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
493        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
494
495        // TODO DO Still can't be removed in this case.
496    }
497
498    /**
499     * Test for:
500     * {@link DevicePolicyManager#removeActiveAdmin}
501     */
502    public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
503        // Need MANAGE_DEVICE_ADMINS for setActiveAdmin.  We'll remove it later.
504        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
506        // Add admin1.
507
508        dpm.setActiveAdmin(admin1, /* replace =*/ false);
509
510        assertTrue(dpm.isAdminActive(admin1));
511        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
512
513        // Broadcast from saveSettingsLocked().
514        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
515                MockUtils.checkIntentAction(
516                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
517                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
518
519        // Remove.  No permissions, but same user, so it'll work.
520        mContext.callerPermissions.clear();
521        dpm.removeActiveAdmin(admin1);
522
523        verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
524                MockUtils.checkIntentAction(
525                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
526                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
527                isNull(String.class),
528                any(BroadcastReceiver.class),
529                eq(dpms.mHandler),
530                eq(Activity.RESULT_OK),
531                isNull(String.class),
532                isNull(Bundle.class));
533
534        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
535
536        // Again broadcast from saveSettingsLocked().
537        verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
538                MockUtils.checkIntentAction(
539                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
540                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
541
542        // TODO Check other internal calls.
543    }
544
545    /**
546     * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
547     */
548    public void testSetDeviceOwner() throws Exception {
549        setDeviceOwner();
550
551        // Try to set a profile owner on the same user, which should fail.
552        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
553        dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
554        try {
555            dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
556            fail("IllegalStateException not thrown");
557        } catch (IllegalStateException expected) {
558            assertTrue("Message was: " + expected.getMessage(),
559                    expected.getMessage().contains("already has a device owner"));
560        }
561
562        // DO admin can't be deactivated.
563        dpm.removeActiveAdmin(admin1);
564        assertTrue(dpm.isAdminActive(admin1));
565
566        // TODO Test getDeviceOwnerName() too. To do so, we need to change
567        // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
568    }
569
570    private void setDeviceOwner() throws Exception {
571        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
572        mContext.callerPermissions.add(permission.MANAGE_USERS);
573        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
574        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
575
576        // In this test, change the caller user to "system".
577        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
578
579        // Make sure admin1 is installed on system user.
580        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
581
582        // Check various get APIs.
583        checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
584
585        // DO needs to be an DA.
586        dpm.setActiveAdmin(admin1, /* replace =*/ false);
587
588        // Fire!
589        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
590
591        // getDeviceOwnerComponent should return the admin1 component.
592        assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
593        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
594
595        // Check various get APIs.
596        checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
597
598        // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
599        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
600        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
601        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
602
603        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
604
605        // Verify internal calls.
606        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
607                eq(admin1.getPackageName()));
608
609        // TODO We should check if the caller has called clearCallerIdentity().
610        verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
611                eq(UserHandle.USER_SYSTEM), eq(false));
612
613        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
614                MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
615                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
616
617        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
618    }
619
620    private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
621        final int origCallingUser = mContext.binder.callingUid;
622        final List origPermissions = new ArrayList(mContext.callerPermissions);
623        mContext.callerPermissions.clear();
624
625        mContext.callerPermissions.add(permission.MANAGE_USERS);
626
627        mContext.binder.callingUid = Process.SYSTEM_UID;
628
629        // TODO Test getDeviceOwnerName() too.  To do so, we need to change
630        // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
631        if (hasDeviceOwner) {
632            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
633            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
634            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
635
636            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
637            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
638            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
639        } else {
640            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
641            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
642            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
643
644            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
645            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
646            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
647        }
648
649        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
650        if (hasDeviceOwner) {
651            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
652            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
653            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
654
655            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
656            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
657            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
658        } else {
659            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
660            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
661            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
662
663            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
664            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
665            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
666        }
667
668        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
669        // Still with MANAGE_USERS.
670        assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
671        assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
672        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
673
674        if (hasDeviceOwner) {
675            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
676            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
677            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
678        } else {
679            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
680            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
681            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
682        }
683
684        mContext.binder.callingUid = Process.SYSTEM_UID;
685        mContext.callerPermissions.remove(permission.MANAGE_USERS);
686        // System can still call "OnAnyUser" without MANAGE_USERS.
687        if (hasDeviceOwner) {
688            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
689            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
690            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
691
692            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
693            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
694            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
695        } else {
696            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
697            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
698            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
699
700            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
701            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
702            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
703        }
704
705        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
706        // Still no MANAGE_USERS.
707        if (hasDeviceOwner) {
708            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
709            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
710            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
711        } else {
712            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
713            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
714            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
715        }
716
717        try {
718            dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
719            fail();
720        } catch (SecurityException expected) {
721        }
722        try {
723            dpm.getDeviceOwnerComponentOnAnyUser();
724            fail();
725        } catch (SecurityException expected) {
726        }
727        try {
728            dpm.getDeviceOwnerUserId();
729            fail();
730        } catch (SecurityException expected) {
731        }
732        try {
733            dpm.getDeviceOwnerNameOnAnyUser();
734            fail();
735        } catch (SecurityException expected) {
736        }
737
738        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
739        // Still no MANAGE_USERS.
740        assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
741        assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
742        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
743
744        try {
745            dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
746            fail();
747        } catch (SecurityException expected) {
748        }
749        try {
750            dpm.getDeviceOwnerComponentOnAnyUser();
751            fail();
752        } catch (SecurityException expected) {
753        }
754        try {
755            dpm.getDeviceOwnerUserId();
756            fail();
757        } catch (SecurityException expected) {
758        }
759        try {
760            dpm.getDeviceOwnerNameOnAnyUser();
761            fail();
762        } catch (SecurityException expected) {
763        }
764
765        // Restore.
766        mContext.binder.callingUid = origCallingUser;
767        mContext.callerPermissions.addAll(origPermissions);
768    }
769
770
771    /**
772     * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
773     */
774    public void testSetDeviceOwner_noSuchPackage() {
775        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
776        mContext.callerPermissions.add(permission.MANAGE_USERS);
777        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
778        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
779
780        // Call from a process on the system user.
781        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
782
783        try {
784            dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
785            fail("Didn't throw IllegalArgumentException");
786        } catch (IllegalArgumentException expected) {
787            assertTrue("Message was: " + expected.getMessage(),
788                    expected.getMessage().contains("Invalid component"));
789        }
790    }
791
792    public void testSetDeviceOwner_failures() throws Exception {
793        // TODO Test more failure cases.  Basically test all chacks in enforceCanSetDeviceOwner().
794    }
795
796    public void testClearDeviceOwner() throws Exception {
797        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
798        mContext.callerPermissions.add(permission.MANAGE_USERS);
799        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
800        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
801
802        // Set admin1 as a DA to the secondary user.
803        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
804
805        dpm.setActiveAdmin(admin1, /* replace =*/ false);
806
807        // Set admin 1 as the DO to the system user.
808
809        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
810        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
811        dpm.setActiveAdmin(admin1, /* replace =*/ false);
812        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
813
814        // Verify internal calls.
815        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
816                eq(admin1.getPackageName()));
817
818        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
819
820        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
821
822        assertTrue(dpm.isAdminActive(admin1));
823        assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
824
825        // Set up other mocks.
826        when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
827
828        // Now call clear.
829        doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
830                eq(admin1.getPackageName()),
831                anyInt());
832
833        // But first pretend the user is locked.  Then it should fail.
834        when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
835        try {
836            dpm.clearDeviceOwnerApp(admin1.getPackageName());
837            fail("Didn't throw IllegalStateException");
838        } catch (IllegalStateException expected) {
839            MoreAsserts.assertContainsRegex(
840                    "User must be running and unlocked", expected.getMessage());
841        }
842
843        when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
844        reset(mContext.userManagerInternal);
845        dpm.clearDeviceOwnerApp(admin1.getPackageName());
846
847        // Now DO shouldn't be set.
848        assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
849
850        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
851                eq(UserHandle.USER_SYSTEM),
852                MockUtils.checkUserRestrictions(),
853                MockUtils.checkUserRestrictions()
854        );
855
856        assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
857
858        // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
859        // and once for clearing it.
860        verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
861                MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
862                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
863        // TODO Check other calls.
864    }
865
866    public void testClearDeviceOwner_fromDifferentUser() throws Exception {
867        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
868        mContext.callerPermissions.add(permission.MANAGE_USERS);
869        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
870        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
871
872        // Set admin1 as a DA to the secondary user.
873        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
874
875        dpm.setActiveAdmin(admin1, /* replace =*/ false);
876
877        // Set admin 1 as the DO to the system user.
878
879        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
880        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
881        dpm.setActiveAdmin(admin1, /* replace =*/ false);
882        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
883
884        // Verify internal calls.
885        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
886                eq(admin1.getPackageName()));
887
888        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
889
890        // Now call clear from the secondary user, which should throw.
891        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
892
893        // Now call clear.
894        doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
895                eq(admin1.getPackageName()),
896                anyInt());
897        try {
898            dpm.clearDeviceOwnerApp(admin1.getPackageName());
899            fail("Didn't throw");
900        } catch (SecurityException e) {
901            assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
902        }
903
904        // DO shouldn't be removed.
905        assertTrue(dpm.isDeviceManaged());
906    }
907
908    public void testSetProfileOwner() throws Exception {
909        setAsProfileOwner(admin1);
910
911        // PO admin can't be deactivated.
912        dpm.removeActiveAdmin(admin1);
913        assertTrue(dpm.isAdminActive(admin1));
914
915        // Try setting DO on the same user, which should fail.
916        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
917        dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
918        try {
919            dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
920            fail("IllegalStateException not thrown");
921        } catch (IllegalStateException expected) {
922            assertTrue("Message was: " + expected.getMessage(),
923                    expected.getMessage().contains("already has a profile owner"));
924        }
925    }
926
927    public void testClearProfileOwner() throws Exception {
928        setAsProfileOwner(admin1);
929
930        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
931
932        assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
933        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
934
935        // First try when the user is locked, which should fail.
936        when(mContext.userManager.isUserUnlocked(anyInt()))
937                .thenReturn(false);
938        try {
939            dpm.clearProfileOwner(admin1);
940            fail("Didn't throw IllegalStateException");
941        } catch (IllegalStateException expected) {
942            MoreAsserts.assertContainsRegex(
943                    "User must be running and unlocked", expected.getMessage());
944        }
945        // Clear, really.
946        when(mContext.userManager.isUserUnlocked(anyInt()))
947                .thenReturn(true);
948        dpm.clearProfileOwner(admin1);
949
950        // Check
951        assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
952        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
953    }
954
955    public void testSetProfileOwner_failures() throws Exception {
956        // TODO Test more failure cases.  Basically test all chacks in enforceCanSetProfileOwner().
957    }
958
959    public void testGetDeviceOwnerAdminLocked() throws Exception {
960        checkDeviceOwnerWithMultipleDeviceAdmins();
961    }
962
963    private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
964        // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
965        // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
966        // make sure it gets the right component from the right user.
967
968        final int ANOTHER_USER_ID = 100;
969        final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
970
971        mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
972
973        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
974        mContext.callerPermissions.add(permission.MANAGE_USERS);
975        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
976        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
977
978        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
979
980        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
981
982        // Make sure the admin packge is installed to each user.
983        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
984        setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
985
986        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
987        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
988
989        setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
990
991
992        // Set active admins to the users.
993        dpm.setActiveAdmin(admin1, /* replace =*/ false);
994        dpm.setActiveAdmin(admin3, /* replace =*/ false);
995
996        dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
997        dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
998
999        dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1000
1001        // Set DO on the first non-system user.
1002        mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1003        assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1004
1005        assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1006
1007        // Then check getDeviceOwnerAdminLocked().
1008        assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1009        assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1010    }
1011
1012    /**
1013     * This essentially tests
1014     * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1015     * private.)
1016     *
1017     * We didn't use to persist the DO component class name, but now we do, and the above method
1018     * finds the right component from a package name upon migration.
1019     */
1020    public void testDeviceOwnerMigration() throws Exception {
1021        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1022        checkDeviceOwnerWithMultipleDeviceAdmins();
1023
1024        // Overwrite the device owner setting and clears the clas name.
1025        dpms.mOwners.setDeviceOwner(
1026                new ComponentName(admin2.getPackageName(), ""),
1027                "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1028        dpms.mOwners.writeDeviceOwner();
1029
1030        // Make sure the DO component name doesn't have a class name.
1031        assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
1032
1033        // Then create a new DPMS to have it load the settings from files.
1034        when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1035                .thenReturn(new Bundle());
1036        initializeDpms();
1037
1038        // Now the DO component name is a full name.
1039        // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1040        // DO.
1041        assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1042    }
1043
1044    public void testSetGetApplicationRestriction() {
1045        setAsProfileOwner(admin1);
1046
1047        {
1048            Bundle rest = new Bundle();
1049            rest.putString("KEY_STRING", "Foo1");
1050            dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1051        }
1052
1053        {
1054            Bundle rest = new Bundle();
1055            rest.putString("KEY_STRING", "Foo2");
1056            dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1057        }
1058
1059        {
1060            Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1061            assertNotNull(returned);
1062            assertEquals(returned.size(), 1);
1063            assertEquals(returned.get("KEY_STRING"), "Foo1");
1064        }
1065
1066        {
1067            Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1068            assertNotNull(returned);
1069            assertEquals(returned.size(), 1);
1070            assertEquals(returned.get("KEY_STRING"), "Foo2");
1071        }
1072
1073        dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1074        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1075    }
1076
1077    public void testApplicationRestrictionsManagingApp() throws Exception {
1078        setAsProfileOwner(admin1);
1079
1080        final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
1081        final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1082        final int appRestrictionsManagerAppId = 20987;
1083        final int appRestrictionsManagerUid = UserHandle.getUid(
1084                DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
1085        doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
1086                eq(appRestrictionsManagerPackage),
1087                eq(DpmMockContext.CALLER_USER_HANDLE));
1088        mContext.binder.callingUid = appRestrictionsManagerUid;
1089
1090        final PackageInfo pi = new PackageInfo();
1091        pi.applicationInfo = new ApplicationInfo();
1092        pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1093        doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1094                eq(appRestrictionsManagerPackage),
1095                anyInt(),
1096                eq(DpmMockContext.CALLER_USER_HANDLE));
1097
1098        // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1099        // delegated that permission yet.
1100        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1101        Bundle rest = new Bundle();
1102        rest.putString("KEY_STRING", "Foo1");
1103        try {
1104            dpm.setApplicationRestrictions(null, "pkg1", rest);
1105            fail("Didn't throw expected SecurityException");
1106        } catch (SecurityException expected) {
1107            MoreAsserts.assertContainsRegex(
1108                    "caller cannot manage application restrictions", expected.getMessage());
1109        }
1110        try {
1111            dpm.getApplicationRestrictions(null, "pkg1");
1112            fail("Didn't throw expected SecurityException");
1113        } catch (SecurityException expected) {
1114            MoreAsserts.assertContainsRegex(
1115                    "caller cannot manage application restrictions", expected.getMessage());
1116        }
1117
1118        // Check via the profile owner that no restrictions were set.
1119        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1120        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1121
1122        // Check the API does not allow setting a non-existent package
1123        try {
1124            dpm.setApplicationRestrictionsManagingPackage(admin1,
1125                    nonExistAppRestrictionsManagerPackage);
1126            fail("Non-existent app set as app restriction manager.");
1127        } catch (PackageManager.NameNotFoundException expected) {
1128            MoreAsserts.assertContainsRegex(
1129                    nonExistAppRestrictionsManagerPackage, expected.getMessage());
1130        }
1131
1132        // Let appRestrictionsManagerPackage manage app restrictions
1133        dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1134        assertEquals(appRestrictionsManagerPackage,
1135                dpm.getApplicationRestrictionsManagingPackage(admin1));
1136
1137        // Now that package should be able to set and retrieve app restrictions.
1138        mContext.binder.callingUid = appRestrictionsManagerUid;
1139        assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1140        dpm.setApplicationRestrictions(null, "pkg1", rest);
1141        Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1142        assertEquals(1, returned.size(), 1);
1143        assertEquals("Foo1", returned.get("KEY_STRING"));
1144
1145        // The same app running on a separate user shouldn't be able to manage app restrictions.
1146        mContext.binder.callingUid = UserHandle.getUid(
1147                UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1148        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1149        try {
1150            dpm.setApplicationRestrictions(null, "pkg1", rest);
1151            fail("Didn't throw expected SecurityException");
1152        } catch (SecurityException expected) {
1153            MoreAsserts.assertContainsRegex(
1154                    "caller cannot manage application restrictions", expected.getMessage());
1155        }
1156
1157        // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1158        // too.
1159        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1160        assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1161        dpm.setApplicationRestrictions(admin1, "pkg1", null);
1162        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1163
1164        // Removing the ability for the package to manage app restrictions.
1165        dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1166        assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1167        mContext.binder.callingUid = appRestrictionsManagerUid;
1168        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1169        try {
1170            dpm.setApplicationRestrictions(null, "pkg1", null);
1171            fail("Didn't throw expected SecurityException");
1172        } catch (SecurityException expected) {
1173            MoreAsserts.assertContainsRegex(
1174                    "caller cannot manage application restrictions", expected.getMessage());
1175        }
1176    }
1177
1178    public void testSetUserRestriction_asDo() throws Exception {
1179        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1180        mContext.callerPermissions.add(permission.MANAGE_USERS);
1181        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1182        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1183
1184        // First, set DO.
1185
1186        // Call from a process on the system user.
1187        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1188
1189        // Make sure admin1 is installed on system user.
1190        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1191
1192        // Call.
1193        dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1194        assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1195                UserHandle.USER_SYSTEM));
1196
1197        // Check that the user restrictions that are enabled by default are set. Then unset them.
1198        String[] defaultRestrictions = UserRestrictionsUtils
1199                        .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1200        DpmTestUtils.assertRestrictions(
1201                DpmTestUtils.newRestrictions(defaultRestrictions),
1202                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1203        );
1204        DpmTestUtils.assertRestrictions(
1205                DpmTestUtils.newRestrictions(defaultRestrictions),
1206                dpm.getUserRestrictions(admin1)
1207        );
1208
1209        for (String restriction : defaultRestrictions) {
1210            dpm.clearUserRestriction(admin1, restriction);
1211        }
1212
1213        DpmTestUtils.assertRestrictions(
1214                DpmTestUtils.newRestrictions(),
1215                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1216        );
1217        DpmTestUtils.assertRestrictions(
1218                DpmTestUtils.newRestrictions(),
1219                dpm.getUserRestrictions(admin1)
1220        );
1221
1222        reset(mContext.userManagerInternal);
1223
1224        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1225        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1226                eq(UserHandle.USER_SYSTEM),
1227                MockUtils.checkUserRestrictions(),
1228                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1229        );
1230        reset(mContext.userManagerInternal);
1231
1232        dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1233        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1234                eq(UserHandle.USER_SYSTEM),
1235                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1236                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1237        );
1238        reset(mContext.userManagerInternal);
1239
1240        DpmTestUtils.assertRestrictions(
1241                DpmTestUtils.newRestrictions(
1242                        UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1243                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1244        );
1245        DpmTestUtils.assertRestrictions(
1246                DpmTestUtils.newRestrictions(
1247                        UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1248                dpm.getUserRestrictions(admin1)
1249        );
1250
1251        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1252        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1253                eq(UserHandle.USER_SYSTEM),
1254                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1255                MockUtils.checkUserRestrictions()
1256        );
1257        reset(mContext.userManagerInternal);
1258
1259        DpmTestUtils.assertRestrictions(
1260                DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1261                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1262        );
1263        DpmTestUtils.assertRestrictions(
1264                DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1265                dpm.getUserRestrictions(admin1)
1266        );
1267
1268        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1269        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1270                eq(UserHandle.USER_SYSTEM),
1271                MockUtils.checkUserRestrictions(),
1272                MockUtils.checkUserRestrictions()
1273        );
1274        reset(mContext.userManagerInternal);
1275
1276        DpmTestUtils.assertRestrictions(
1277                DpmTestUtils.newRestrictions(),
1278                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1279        );
1280        DpmTestUtils.assertRestrictions(
1281                DpmTestUtils.newRestrictions(),
1282                dpm.getUserRestrictions(admin1)
1283        );
1284
1285        // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1286        // DO sets them, the scope is global.
1287        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1288        reset(mContext.userManagerInternal);
1289        dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1290        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1291                eq(UserHandle.USER_SYSTEM),
1292                MockUtils.checkUserRestrictions(),
1293                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1294                        UserManager.DISALLOW_UNMUTE_MICROPHONE)
1295        );
1296        reset(mContext.userManagerInternal);
1297
1298        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1299        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1300
1301
1302        // More tests.
1303        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1304        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1305                eq(UserHandle.USER_SYSTEM),
1306                MockUtils.checkUserRestrictions(),
1307                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1308        );
1309        reset(mContext.userManagerInternal);
1310
1311        dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1312        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1313                eq(UserHandle.USER_SYSTEM),
1314                MockUtils.checkUserRestrictions(),
1315                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1316                        UserManager.DISALLOW_ADD_USER)
1317        );
1318        reset(mContext.userManagerInternal);
1319
1320        dpm.setCameraDisabled(admin1, true);
1321        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1322                eq(UserHandle.USER_SYSTEM),
1323                // DISALLOW_CAMERA will be applied to both local and global.
1324                MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1325                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1326                        UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1327        );
1328        reset(mContext.userManagerInternal);
1329
1330        // Set up another DA and let it disable camera.  Now DISALLOW_CAMERA will only be applied
1331        // locally.
1332        dpm.setCameraDisabled(admin1, false);
1333        reset(mContext.userManagerInternal);
1334
1335        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1336        dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1337        dpm.setCameraDisabled(admin2, true);
1338
1339        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1340                eq(UserHandle.USER_SYSTEM),
1341                // DISALLOW_CAMERA will be applied to both local and global.
1342                MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1343                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1344                        UserManager.DISALLOW_ADD_USER)
1345        );
1346        reset(mContext.userManagerInternal);
1347        // TODO Make sure restrictions are written to the file.
1348    }
1349
1350    public void testSetUserRestriction_asPo() {
1351        setAsProfileOwner(admin1);
1352
1353        DpmTestUtils.assertRestrictions(
1354                DpmTestUtils.newRestrictions(),
1355                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1356                        .ensureUserRestrictions()
1357        );
1358
1359        dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1360        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1361                eq(DpmMockContext.CALLER_USER_HANDLE),
1362                MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1363                isNull(Bundle.class)
1364        );
1365        reset(mContext.userManagerInternal);
1366
1367        dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1368        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1369                eq(DpmMockContext.CALLER_USER_HANDLE),
1370                MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1371                        UserManager.DISALLOW_OUTGOING_CALLS),
1372                isNull(Bundle.class)
1373        );
1374        reset(mContext.userManagerInternal);
1375
1376        DpmTestUtils.assertRestrictions(
1377                DpmTestUtils.newRestrictions(
1378                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1379                        UserManager.DISALLOW_OUTGOING_CALLS
1380                ),
1381                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1382                        .ensureUserRestrictions()
1383        );
1384        DpmTestUtils.assertRestrictions(
1385                DpmTestUtils.newRestrictions(
1386                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1387                        UserManager.DISALLOW_OUTGOING_CALLS
1388                ),
1389                dpm.getUserRestrictions(admin1)
1390        );
1391
1392        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1393        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1394                eq(DpmMockContext.CALLER_USER_HANDLE),
1395                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1396                isNull(Bundle.class)
1397        );
1398        reset(mContext.userManagerInternal);
1399
1400        DpmTestUtils.assertRestrictions(
1401                DpmTestUtils.newRestrictions(
1402                        UserManager.DISALLOW_OUTGOING_CALLS
1403                ),
1404                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1405                        .ensureUserRestrictions()
1406        );
1407        DpmTestUtils.assertRestrictions(
1408                DpmTestUtils.newRestrictions(
1409                        UserManager.DISALLOW_OUTGOING_CALLS
1410                ),
1411                dpm.getUserRestrictions(admin1)
1412        );
1413
1414        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1415        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1416                eq(DpmMockContext.CALLER_USER_HANDLE),
1417                MockUtils.checkUserRestrictions(),
1418                isNull(Bundle.class)
1419        );
1420        reset(mContext.userManagerInternal);
1421
1422        DpmTestUtils.assertRestrictions(
1423                DpmTestUtils.newRestrictions(),
1424                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1425                        .ensureUserRestrictions()
1426        );
1427        DpmTestUtils.assertRestrictions(
1428                DpmTestUtils.newRestrictions(),
1429                dpm.getUserRestrictions(admin1)
1430        );
1431
1432        // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1433        // though when DO sets them they'll be applied globally.
1434        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1435        reset(mContext.userManagerInternal);
1436        dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1437        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1438                eq(DpmMockContext.CALLER_USER_HANDLE),
1439                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1440                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1441                isNull(Bundle.class)
1442        );
1443        reset(mContext.userManagerInternal);
1444
1445        dpm.setCameraDisabled(admin1, true);
1446        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1447                eq(DpmMockContext.CALLER_USER_HANDLE),
1448                MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1449                        UserManager.DISALLOW_ADJUST_VOLUME,
1450                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1451                isNull(Bundle.class)
1452        );
1453        reset(mContext.userManagerInternal);
1454
1455        // TODO Make sure restrictions are written to the file.
1456    }
1457
1458    public void testGetMacAddress() throws Exception {
1459        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1460        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1461        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1462
1463        // In this test, change the caller user to "system".
1464        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1465
1466        // Make sure admin1 is installed on system user.
1467        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1468
1469        // Test 1. Caller doesn't have DO or DA.
1470        try {
1471            dpm.getWifiMacAddress(admin1);
1472            fail();
1473        } catch (SecurityException e) {
1474            MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
1475        }
1476
1477        // DO needs to be an DA.
1478        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1479        assertTrue(dpm.isAdminActive(admin1));
1480
1481        // Test 2. Caller has DA, but not DO.
1482        try {
1483            dpm.getWifiMacAddress(admin1);
1484            fail();
1485        } catch (SecurityException e) {
1486            MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
1487        }
1488
1489        // Test 3. Caller has PO, but not DO.
1490        assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1491        try {
1492            dpm.getWifiMacAddress(admin1);
1493            fail();
1494        } catch (SecurityException e) {
1495            MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
1496        }
1497
1498        // Remove PO.
1499        dpm.clearProfileOwner(admin1);
1500        dpm.setActiveAdmin(admin1, false);
1501        // Test 4, Caller is DO now.
1502        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1503
1504        // 4-1.  But no WifiInfo.
1505        assertNull(dpm.getWifiMacAddress(admin1));
1506
1507        // 4-2.  Returns WifiInfo, but with the default MAC.
1508        when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
1509        assertNull(dpm.getWifiMacAddress(admin1));
1510
1511        // 4-3. With a real MAC address.
1512        final WifiInfo wi = new WifiInfo();
1513        wi.setMacAddress("11:22:33:44:55:66");
1514        when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
1515        assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
1516    }
1517
1518    public void testReboot() throws Exception {
1519        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1520        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1521
1522        // In this test, change the caller user to "system".
1523        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1524
1525        // Make sure admin1 is installed on system user.
1526        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1527
1528        // Set admin1 as DA.
1529        dpm.setActiveAdmin(admin1, false);
1530        assertTrue(dpm.isAdminActive(admin1));
1531        try {
1532            dpm.reboot(admin1);
1533            fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1534        } catch (SecurityException expected) {
1535            MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1536        }
1537
1538        // Set admin1 as PO.
1539        assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1540        try {
1541            dpm.reboot(admin1);
1542            fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1543        } catch (SecurityException expected) {
1544            MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1545        }
1546
1547        // Remove PO and add DO.
1548        dpm.clearProfileOwner(admin1);
1549        dpm.setActiveAdmin(admin1, false);
1550        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1551
1552        // admin1 is DO.
1553        // Set current call state of device to ringing.
1554        when(mContext.telephonyManager.getCallState())
1555                .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1556        try {
1557            dpm.reboot(admin1);
1558            fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1559        } catch (IllegalStateException expected) {
1560            MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1561        }
1562
1563        // Set current call state of device to dialing/active.
1564        when(mContext.telephonyManager.getCallState())
1565                .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1566        try {
1567            dpm.reboot(admin1);
1568            fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1569        } catch (IllegalStateException expected) {
1570            MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1571        }
1572
1573        // Set current call state of device to idle.
1574        when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
1575        dpm.reboot(admin1);
1576    }
1577
1578    public void testSetGetSupportText() {
1579        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1580        dpm.setActiveAdmin(admin1, true);
1581        dpm.setActiveAdmin(admin2, true);
1582        mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1583
1584        // Null default support messages.
1585        {
1586            assertNull(dpm.getLongSupportMessage(admin1));
1587            assertNull(dpm.getShortSupportMessage(admin1));
1588            mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1589            assertNull(dpm.getShortSupportMessageForUser(admin1,
1590                    DpmMockContext.CALLER_USER_HANDLE));
1591            assertNull(dpm.getLongSupportMessageForUser(admin1,
1592                    DpmMockContext.CALLER_USER_HANDLE));
1593            mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1594        }
1595
1596        // Only system can call the per user versions.
1597        {
1598            try {
1599                dpm.getShortSupportMessageForUser(admin1,
1600                        DpmMockContext.CALLER_USER_HANDLE);
1601                fail("Only system should be able to call getXXXForUser versions");
1602            } catch (SecurityException expected) {
1603                MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1604            }
1605            try {
1606                dpm.getLongSupportMessageForUser(admin1,
1607                        DpmMockContext.CALLER_USER_HANDLE);
1608                fail("Only system should be able to call getXXXForUser versions");
1609            } catch (SecurityException expected) {
1610                MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1611            }
1612        }
1613
1614        // Can't set message for admin in another uid.
1615        {
1616            mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1617            try {
1618                dpm.setShortSupportMessage(admin1, "Some text");
1619                fail("Admins should only be able to change their own support text.");
1620            } catch (SecurityException expected) {
1621                MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1622            }
1623            mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1624        }
1625
1626        // Set/Get short returns what it sets and other admins text isn't changed.
1627        {
1628            final String supportText = "Some text to test with.";
1629            dpm.setShortSupportMessage(admin1, supportText);
1630            assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1631            assertNull(dpm.getLongSupportMessage(admin1));
1632            assertNull(dpm.getShortSupportMessage(admin2));
1633
1634            mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1635            assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1636                    DpmMockContext.CALLER_USER_HANDLE));
1637            assertNull(dpm.getShortSupportMessageForUser(admin2,
1638                    DpmMockContext.CALLER_USER_HANDLE));
1639            assertNull(dpm.getLongSupportMessageForUser(admin1,
1640                    DpmMockContext.CALLER_USER_HANDLE));
1641            mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1642
1643            dpm.setShortSupportMessage(admin1, null);
1644            assertNull(dpm.getShortSupportMessage(admin1));
1645        }
1646
1647        // Set/Get long returns what it sets and other admins text isn't changed.
1648        {
1649            final String supportText = "Some text to test with.\nWith more text.";
1650            dpm.setLongSupportMessage(admin1, supportText);
1651            assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1652            assertNull(dpm.getShortSupportMessage(admin1));
1653            assertNull(dpm.getLongSupportMessage(admin2));
1654
1655            mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1656            assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1657                    DpmMockContext.CALLER_USER_HANDLE));
1658            assertNull(dpm.getLongSupportMessageForUser(admin2,
1659                    DpmMockContext.CALLER_USER_HANDLE));
1660            assertNull(dpm.getShortSupportMessageForUser(admin1,
1661                    DpmMockContext.CALLER_USER_HANDLE));
1662            mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1663
1664            dpm.setLongSupportMessage(admin1, null);
1665            assertNull(dpm.getLongSupportMessage(admin1));
1666        }
1667    }
1668
1669    /**
1670     * Test for:
1671     * {@link DevicePolicyManager#setAffiliationIds}
1672     * {@link DevicePolicyManager#getAffiliationIds}
1673     * {@link DevicePolicyManager#isAffiliatedUser}
1674     */
1675    public void testUserAffiliation() throws Exception {
1676        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1677        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1678        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1679
1680        // Check that the system user is unaffiliated.
1681        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1682        assertFalse(dpm.isAffiliatedUser());
1683
1684        // Set a device owner on the system user. Check that the system user becomes affiliated.
1685        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1686        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1687        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1688        assertTrue(dpm.isAffiliatedUser());
1689        assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
1690
1691        // Install a profile owner. Check that the test user is unaffiliated.
1692        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1693        setAsProfileOwner(admin2);
1694        assertFalse(dpm.isAffiliatedUser());
1695        assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
1696
1697        // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1698        // unaffiliated.
1699        final List<String> userAffiliationIds = new ArrayList<>();
1700        userAffiliationIds.add("red");
1701        userAffiliationIds.add("green");
1702        userAffiliationIds.add("blue");
1703        dpm.setAffiliationIds(admin2, userAffiliationIds);
1704        MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
1705        assertFalse(dpm.isAffiliatedUser());
1706
1707        // Have the device owner specify a set of affiliation ids that do not intersect with those
1708        // specified by the profile owner. Check that the test user remains unaffiliated.
1709        final List<String> deviceAffiliationIds = new ArrayList<>();
1710        deviceAffiliationIds.add("cyan");
1711        deviceAffiliationIds.add("yellow");
1712        deviceAffiliationIds.add("magenta");
1713        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1714        dpm.setAffiliationIds(admin1, deviceAffiliationIds);
1715        MoreAsserts.assertContentsInAnyOrder(
1716            dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
1717        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1718        assertFalse(dpm.isAffiliatedUser());
1719
1720        // Have the profile owner specify a set of affiliation ids that intersect with those
1721        // specified by the device owner. Check that the test user becomes affiliated.
1722        userAffiliationIds.add("yellow");
1723        dpm.setAffiliationIds(admin2, userAffiliationIds);
1724        MoreAsserts.assertContentsInAnyOrder(
1725            dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
1726        assertTrue(dpm.isAffiliatedUser());
1727
1728        // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1729        dpm.setAffiliationIds(admin2, Collections.emptyList());
1730        assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
1731        assertFalse(dpm.isAffiliatedUser());
1732
1733        // Check that the system user remains affiliated.
1734        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1735        assertTrue(dpm.isAffiliatedUser());
1736    }
1737
1738    public void testGetUserProvisioningState_defaultResult() {
1739        assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1740    }
1741
1742    public void testSetUserProvisioningState_permission() throws Exception {
1743        setupProfileOwner();
1744        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1745
1746        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1747                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1748    }
1749
1750    public void testSetUserProvisioningState_unprivileged() throws Exception {
1751        setupProfileOwner();
1752        try {
1753            dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1754                    DpmMockContext.CALLER_USER_HANDLE);
1755            fail("Expected SecurityException");
1756        } catch (SecurityException expected) {
1757        }
1758    }
1759
1760    public void testSetUserProvisioningState_noManagement() {
1761        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1762        try {
1763            dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1764                    DpmMockContext.CALLER_USER_HANDLE);
1765            fail("IllegalStateException expected");
1766        } catch (IllegalStateException e) {
1767            MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1768                    e.getMessage());
1769        }
1770        assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1771    }
1772
1773    public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1774        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1775        setupDeviceOwner();
1776        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1777
1778        exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1779                DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1780                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1781    }
1782
1783    public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1784            throws Exception {
1785        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1786        setupDeviceOwner();
1787        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1788
1789        exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1790                DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1791                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1792    }
1793
1794    public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1795        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1796        setupDeviceOwner();
1797        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1798
1799        exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1800                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1801    }
1802
1803    public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1804            throws Exception {
1805        setupProfileOwner();
1806        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1807
1808        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1809                DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1810                DevicePolicyManager.STATE_USER_UNMANAGED);
1811    }
1812
1813    public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1814            throws Exception {
1815        setupProfileOwner();
1816        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1817
1818        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1819                DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1820                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1821    }
1822
1823    public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1824        setupProfileOwner();
1825        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1826
1827        exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1828                DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1829    }
1830
1831    public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1832        setupProfileOwner();
1833        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1834
1835        try {
1836            exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1837                    DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1838                    DevicePolicyManager.STATE_USER_UNMANAGED);
1839            fail("Expected IllegalStateException");
1840        } catch (IllegalStateException e) {
1841            MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1842                    e.getMessage());
1843        }
1844    }
1845
1846    public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1847            throws Exception {
1848        setupProfileOwner();
1849        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1850
1851        try {
1852            exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1853                    DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1854                    DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1855            fail("Expected IllegalStateException");
1856        } catch (IllegalStateException e) {
1857            MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1858                    e.getMessage());
1859        }
1860    }
1861
1862    private void exerciseUserProvisioningTransitions(int userId, int... states) {
1863        assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1864        for (int state : states) {
1865            dpm.setUserProvisioningState(state, userId);
1866            assertEquals(state, dpm.getUserProvisioningState());
1867        }
1868    }
1869
1870    private void setupProfileOwner() throws Exception {
1871        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1872
1873        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1874        dpm.setActiveAdmin(admin1, false);
1875        assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1876
1877        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1878    }
1879
1880    private void setupDeviceOwner() throws Exception {
1881        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1882
1883        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1884        dpm.setActiveAdmin(admin1, false);
1885        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1886
1887        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1888    }
1889
1890    public void testSetMaximumTimeToLock() {
1891        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1892
1893        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1894        dpm.setActiveAdmin(admin2, /* replace =*/ false);
1895
1896        reset(mMockContext.powerManagerInternal);
1897        reset(mMockContext.settings);
1898
1899        dpm.setMaximumTimeToLock(admin1, 0);
1900        verifyScreenTimeoutCall(null, false);
1901        reset(mMockContext.powerManagerInternal);
1902        reset(mMockContext.settings);
1903
1904        dpm.setMaximumTimeToLock(admin1, 1);
1905        verifyScreenTimeoutCall(1, true);
1906        reset(mMockContext.powerManagerInternal);
1907        reset(mMockContext.settings);
1908
1909        dpm.setMaximumTimeToLock(admin2, 10);
1910        verifyScreenTimeoutCall(null, false);
1911        reset(mMockContext.powerManagerInternal);
1912        reset(mMockContext.settings);
1913
1914        dpm.setMaximumTimeToLock(admin1, 5);
1915        verifyScreenTimeoutCall(5, true);
1916        reset(mMockContext.powerManagerInternal);
1917        reset(mMockContext.settings);
1918
1919        dpm.setMaximumTimeToLock(admin2, 4);
1920        verifyScreenTimeoutCall(4, true);
1921        reset(mMockContext.powerManagerInternal);
1922        reset(mMockContext.settings);
1923
1924        dpm.setMaximumTimeToLock(admin1, 0);
1925        reset(mMockContext.powerManagerInternal);
1926        reset(mMockContext.settings);
1927
1928        dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1929        verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1930        reset(mMockContext.powerManagerInternal);
1931        reset(mMockContext.settings);
1932
1933        dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1934        verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1935        reset(mMockContext.powerManagerInternal);
1936        reset(mMockContext.settings);
1937
1938        dpm.setMaximumTimeToLock(admin2, 10);
1939        verifyScreenTimeoutCall(10, true);
1940        reset(mMockContext.powerManagerInternal);
1941        reset(mMockContext.settings);
1942
1943        // There's no restriction; shold be set to MAX.
1944        dpm.setMaximumTimeToLock(admin2, 0);
1945        verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1946    }
1947
1948    public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1949        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1950        setupDeviceOwner();
1951        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1952
1953        final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1954        final long ONE_MINUTE = 60 * 1000;
1955
1956        // aggregation should be the default if unset by any admin
1957        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1958                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1959
1960        // admin not participating by default
1961        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1962
1963        //clamping from the top
1964        dpm.setRequiredStrongAuthTimeout(admin1,
1965                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1966        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1967                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1968        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1969                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1970
1971        // 0 means default
1972        dpm.setRequiredStrongAuthTimeout(admin1, 0);
1973        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1974        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1975                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1976
1977        // clamping from the bottom
1978        dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1979        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1980        assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1981
1982        // value within range
1983        dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1984        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1985                + ONE_MINUTE);
1986        assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1987                + ONE_MINUTE);
1988
1989        // reset to default
1990        dpm.setRequiredStrongAuthTimeout(admin1, 0);
1991        assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1992        assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1993                DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1994
1995        // negative value
1996        try {
1997            dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1998            fail("Didn't throw IllegalArgumentException");
1999        } catch (IllegalArgumentException iae) {
2000        }
2001    }
2002
2003    private void verifyScreenTimeoutCall(Integer expectedTimeout,
2004            boolean shouldStayOnWhilePluggedInBeCleared) {
2005        if (expectedTimeout == null) {
2006            verify(mMockContext.powerManagerInternal, times(0))
2007                    .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2008        } else {
2009            verify(mMockContext.powerManagerInternal, times(1))
2010                    .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2011        }
2012        // TODO Verify calls to settingsGlobalPutInt.  Tried but somehow mockito threw
2013        // UnfinishedVerificationException.
2014    }
2015
2016    private void setup_DeviceAdminFeatureOff() throws Exception {
2017        when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2018                .thenReturn(false);
2019        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2020                .thenReturn(false);
2021        initializeDpms();
2022        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2023        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2024                .thenReturn(true);
2025        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2026
2027        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2028    }
2029
2030    public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2031        setup_DeviceAdminFeatureOff();
2032        mContext.packageName = admin1.getPackageName();
2033        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2034        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2035        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2036        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2037                false);
2038        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2039    }
2040
2041    public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2042        setup_DeviceAdminFeatureOff();
2043        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2044        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2045                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2046        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2047                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2048        assertCheckProvisioningPreCondition(
2049                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2050                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2051        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2052                DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2053    }
2054
2055    private void setup_ManagedProfileFeatureOff() throws Exception {
2056        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2057                .thenReturn(false);
2058        initializeDpms();
2059        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2060        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2061                .thenReturn(true);
2062        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2063
2064        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2065    }
2066
2067    public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2068        setup_ManagedProfileFeatureOff();
2069        mContext.packageName = admin1.getPackageName();
2070        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2071        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2072        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2073        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2074                false);
2075        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2076
2077        // Test again when split user is on
2078        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2079        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2080        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2081        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2082                true);
2083        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2084    }
2085
2086    public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2087        setup_ManagedProfileFeatureOff();
2088        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2089        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2090                DevicePolicyManager.CODE_OK);
2091        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2092                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2093        assertCheckProvisioningPreCondition(
2094                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2095                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2096        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2097                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2098
2099        // Test again when split user is on
2100        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2101        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2102                DevicePolicyManager.CODE_OK);
2103        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2104                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2105        assertCheckProvisioningPreCondition(
2106                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2107                DevicePolicyManager.CODE_OK);
2108        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2109                DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2110    }
2111
2112    private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
2113        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2114                .thenReturn(true);
2115        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2116        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2117                .thenReturn(true);
2118        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2119
2120        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2121    }
2122
2123    public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2124        setup_nonSplitUser_firstBoot_primaryUser();
2125        mContext.packageName = admin1.getPackageName();
2126        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2127        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2128        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2129        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2130                false /* because of non-split user */);
2131        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2132                false /* because of non-split user */);
2133    }
2134
2135    public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
2136            throws Exception {
2137        setup_nonSplitUser_firstBoot_primaryUser();
2138        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2139        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2140                DevicePolicyManager.CODE_OK);
2141        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2142                DevicePolicyManager.CODE_OK);
2143        assertCheckProvisioningPreCondition(
2144                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2145                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2146        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2147                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2148    }
2149
2150    private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
2151        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2152                .thenReturn(true);
2153        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2154        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2155                .thenReturn(true);
2156        setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2157
2158        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2159    }
2160
2161    public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2162            throws Exception {
2163        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2164        mContext.packageName = admin1.getPackageName();
2165        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2166        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2167                false/* because of completed device setup */);
2168        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2169        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2170                false/* because of non-split user */);
2171        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2172                false/* because of non-split user */);
2173    }
2174
2175    public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2176            throws Exception {
2177        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2178        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2179        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2180                DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2181        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2182                DevicePolicyManager.CODE_OK);
2183        assertCheckProvisioningPreCondition(
2184                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2185                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2186        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2187                DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2188    }
2189
2190    public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception {
2191        setDeviceOwner();
2192        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2193        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2194        mContext.packageName = admin1.getPackageName();
2195
2196        // COMP mode is allowed.
2197        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2198
2199        when(mContext.userManager.hasUserRestriction(
2200                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2201                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2202                .thenReturn(true);
2203
2204        // The DO should be allowed to initiate provisioning if it set the restriction itself.
2205        when(mContext.userManager.getUserRestrictionSource(
2206                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2207                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2208                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2209        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2210
2211        // The DO should not be allowed to initiate provisioning if the restriction is set by
2212        // another entity.
2213        when(mContext.userManager.getUserRestrictionSource(
2214                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2215                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2216                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2217        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2218    }
2219
2220    public void
2221    testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception {
2222        setDeviceOwner();
2223        setup_nonSplitUser_afterDeviceSetup_primaryUser();
2224        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2225
2226        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2227                DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2228
2229        // COMP mode is allowed.
2230        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2231                DevicePolicyManager.CODE_OK);
2232
2233        // And other DPCs can also provisioning a managed profile (DO + BYOD case).
2234        assertCheckProvisioningPreCondition(
2235                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2236                "some.other.dpc.package.name",
2237                DevicePolicyManager.CODE_OK);
2238
2239        when(mContext.userManager.hasUserRestriction(
2240                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2241                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2242                .thenReturn(true);
2243
2244        // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2245        // other packages should be forbidden.
2246        when(mContext.userManager.getUserRestrictionSource(
2247                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2248                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2249                .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2250        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2251                DevicePolicyManager.CODE_OK);
2252        assertCheckProvisioningPreCondition(
2253                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2254                "some.other.dpc.package.name",
2255                DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2256
2257        // The DO should not be allowed to initiate provisioning if the restriction is set by
2258        // another entity.
2259        when(mContext.userManager.getUserRestrictionSource(
2260                eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2261                eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2262                .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2263        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2264                DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2265                assertCheckProvisioningPreCondition(
2266                DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2267                "some.other.dpc.package.name",
2268                DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2269    }
2270
2271    private void setup_splitUser_firstBoot_systemUser() throws Exception {
2272        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2273                .thenReturn(true);
2274        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2275        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2276                .thenReturn(false);
2277        setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2278
2279        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2280    }
2281
2282    public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2283        setup_splitUser_firstBoot_systemUser();
2284        mContext.packageName = admin1.getPackageName();
2285        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2286        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2287        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2288                false /* because canAddMoreManagedProfiles returns false */);
2289        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2290                true);
2291        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2292                false/* because calling uid is system user */);
2293    }
2294
2295    public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2296            throws Exception {
2297        setup_splitUser_firstBoot_systemUser();
2298        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2299        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2300                DevicePolicyManager.CODE_OK);
2301        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2302                DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2303        assertCheckProvisioningPreCondition(
2304                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2305                DevicePolicyManager.CODE_OK);
2306        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2307                DevicePolicyManager.CODE_SYSTEM_USER);
2308    }
2309
2310    private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
2311        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2312                .thenReturn(true);
2313        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2314        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2315                .thenReturn(false);
2316        setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2317
2318        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2319    }
2320
2321    public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2322        setup_splitUser_afterDeviceSetup_systemUser();
2323        mContext.packageName = admin1.getPackageName();
2324        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2325        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2326                true/* it's undefined behavior. Can be changed into false in the future */);
2327        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2328                false /* because canAddMoreManagedProfiles returns false */);
2329        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2330                true/* it's undefined behavior. Can be changed into false in the future */);
2331        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2332                false/* because calling uid is system user */);
2333    }
2334
2335    public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2336            throws Exception {
2337        setup_splitUser_afterDeviceSetup_systemUser();
2338        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2339        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2340                DevicePolicyManager.CODE_OK);
2341        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2342                DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2343        assertCheckProvisioningPreCondition(
2344                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2345                DevicePolicyManager.CODE_OK);
2346        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2347                DevicePolicyManager.CODE_SYSTEM_USER);
2348    }
2349
2350    private void setup_splitUser_firstBoot_primaryUser() throws Exception {
2351        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2352                .thenReturn(true);
2353        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2354        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2355                true)).thenReturn(true);
2356        setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2357
2358        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2359    }
2360
2361    public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2362        setup_splitUser_firstBoot_primaryUser();
2363        mContext.packageName = admin1.getPackageName();
2364        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2365        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2366        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2367        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2368                true);
2369        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2370    }
2371
2372    public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
2373            throws Exception {
2374        setup_splitUser_firstBoot_primaryUser();
2375        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2376        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2377                DevicePolicyManager.CODE_OK);
2378        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2379                DevicePolicyManager.CODE_OK);
2380        assertCheckProvisioningPreCondition(
2381                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2382                DevicePolicyManager.CODE_OK);
2383        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2384                DevicePolicyManager.CODE_OK);
2385    }
2386
2387    private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
2388        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2389                .thenReturn(true);
2390        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2391        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2392                true)).thenReturn(true);
2393        setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2394
2395        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2396    }
2397
2398    public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2399            throws Exception {
2400        setup_splitUser_afterDeviceSetup_primaryUser();
2401        mContext.packageName = admin1.getPackageName();
2402        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2403        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2404                true/* it's undefined behavior. Can be changed into false in the future */);
2405        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2406        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2407                true/* it's undefined behavior. Can be changed into false in the future */);
2408        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2409                false/* because user setup completed */);
2410    }
2411
2412    public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
2413            throws Exception {
2414        setup_splitUser_afterDeviceSetup_primaryUser();
2415        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2416        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2417                DevicePolicyManager.CODE_OK);
2418        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2419                DevicePolicyManager.CODE_OK);
2420        assertCheckProvisioningPreCondition(
2421                DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2422                DevicePolicyManager.CODE_OK);
2423        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2424                DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2425    }
2426
2427    private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
2428        setDeviceOwner();
2429
2430        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2431                .thenReturn(true);
2432        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2433        when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2434                .thenReturn(false);
2435        setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2436
2437        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2438    }
2439
2440    public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2441            throws Exception {
2442        setup_provisionManagedProfileWithDeviceOwner_systemUser();
2443        mContext.packageName = admin1.getPackageName();
2444        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2445        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2446                false /* can't provision managed profile on system user */);
2447    }
2448
2449    public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
2450            throws Exception {
2451        setup_provisionManagedProfileWithDeviceOwner_systemUser();
2452        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2453        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2454                DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2455    }
2456
2457    private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
2458        setDeviceOwner();
2459
2460        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2461                .thenReturn(true);
2462        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2463        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2464                true)).thenReturn(true);
2465        setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2466
2467        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2468    }
2469
2470    public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2471            throws Exception {
2472        setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2473        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2474        mContext.packageName = admin1.getPackageName();
2475        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2476    }
2477
2478    public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
2479            throws Exception {
2480        setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2481        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2482
2483        // COMP mode is allowed.
2484        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2485                DevicePolicyManager.CODE_OK);
2486    }
2487
2488    private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
2489        setDeviceOwner();
2490
2491        when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2492                .thenReturn(true);
2493        when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2494        when(mContext.userManager.hasUserRestriction(
2495                eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2496                eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
2497                .thenReturn(true);
2498        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2499                false /* we can't remove a managed profile */)).thenReturn(false);
2500        when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2501                true)).thenReturn(true);
2502        setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2503
2504        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2505    }
2506
2507    public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2508            throws Exception {
2509        setup_provisionManagedProfileCantRemoveUser_primaryUser();
2510        mContext.packageName = admin1.getPackageName();
2511        setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2512        assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2513    }
2514
2515    public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2516            throws Exception {
2517        setup_provisionManagedProfileCantRemoveUser_primaryUser();
2518        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2519        assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2520                DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2521    }
2522
2523    public void testCheckProvisioningPreCondition_permission() {
2524        // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2525        try {
2526            dpm.checkProvisioningPreCondition(
2527                    DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
2528            fail("Didn't throw SecurityException");
2529        } catch (SecurityException expected) {
2530        }
2531    }
2532
2533    public void testForceUpdateUserSetupComplete_permission() {
2534        // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2535        try {
2536            dpm.forceUpdateUserSetupComplete();
2537            fail("Didn't throw SecurityException");
2538        } catch (SecurityException expected) {
2539        }
2540    }
2541
2542    public void testForceUpdateUserSetupComplete_systemUser() {
2543        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2544        // GIVEN calling from user 20
2545        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2546        try {
2547            dpm.forceUpdateUserSetupComplete();
2548            fail("Didn't throw SecurityException");
2549        } catch (SecurityException expected) {
2550        }
2551    }
2552
2553    public void testForceUpdateUserSetupComplete_userbuild() {
2554        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2555        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2556
2557        final int userId = UserHandle.USER_SYSTEM;
2558        // GIVEN userComplete is false in SettingsProvider
2559        setUserSetupCompleteForUser(false, userId);
2560
2561        // GIVEN userComplete is true in DPM
2562        DevicePolicyManagerService.DevicePolicyData userData =
2563                new DevicePolicyManagerService.DevicePolicyData(userId);
2564        userData.mUserSetupComplete = true;
2565        dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2566
2567        // GIVEN it's user build
2568        mContext.buildMock.isDebuggable = false;
2569
2570        assertTrue(dpms.hasUserSetupCompleted());
2571
2572        dpm.forceUpdateUserSetupComplete();
2573
2574        // THEN the state in dpms is not changed
2575        assertTrue(dpms.hasUserSetupCompleted());
2576    }
2577
2578    public void testForceUpdateUserSetupComplete_userDebugbuild() {
2579        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2580        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2581
2582        final int userId = UserHandle.USER_SYSTEM;
2583        // GIVEN userComplete is false in SettingsProvider
2584        setUserSetupCompleteForUser(false, userId);
2585
2586        // GIVEN userComplete is true in DPM
2587        DevicePolicyManagerService.DevicePolicyData userData =
2588                new DevicePolicyManagerService.DevicePolicyData(userId);
2589        userData.mUserSetupComplete = true;
2590        dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2591
2592        // GIVEN it's userdebug build
2593        mContext.buildMock.isDebuggable = true;
2594
2595        assertTrue(dpms.hasUserSetupCompleted());
2596
2597        dpm.forceUpdateUserSetupComplete();
2598
2599        // THEN the state in dpms is not changed
2600        assertFalse(dpms.hasUserSetupCompleted());
2601    }
2602
2603    private void clearDeviceOwner() throws Exception {
2604        final long ident = mContext.binder.clearCallingIdentity();
2605        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2606        doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2607                .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2608        dpm.clearDeviceOwnerApp(admin1.getPackageName());
2609        mContext.binder.restoreCallingIdentity(ident);
2610    }
2611
2612    public void testGetLastSecurityLogRetrievalTime() throws Exception {
2613        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2614        setupDeviceOwner();
2615        when(mContext.userManager.getUserCount()).thenReturn(1);
2616        when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2617                .thenReturn(true);
2618
2619        // No logs were retrieved so far.
2620        assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
2621
2622        // Enabling logging should not change the timestamp.
2623        dpm.setSecurityLoggingEnabled(admin1, true);
2624        assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
2625
2626        // Retrieving the logs should update the timestamp.
2627        final long beforeRetrieval = System.currentTimeMillis();
2628        dpm.retrieveSecurityLogs(admin1);
2629        final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
2630        final long afterRetrieval = System.currentTimeMillis();
2631        assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2632        assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2633
2634        // Retrieving the pre-boot logs should update the timestamp.
2635        Thread.sleep(2);
2636        dpm.retrievePreRebootSecurityLogs(admin1);
2637        final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
2638        assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2639
2640        // Checking the timestamp again should not change it.
2641        Thread.sleep(2);
2642        assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2643
2644        // Retrieving the logs again should update the timestamp.
2645        dpm.retrieveSecurityLogs(admin1);
2646        final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
2647        assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2648
2649        // Disabling logging should not change the timestamp.
2650        Thread.sleep(2);
2651        dpm.setSecurityLoggingEnabled(admin1, false);
2652        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2653
2654        // Restarting the DPMS should not lose the timestamp.
2655        initializeDpms();
2656        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2657
2658        // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2659        mContext.binder.callingUid = 1234567;
2660        mContext.callerPermissions.add(permission.MANAGE_USERS);
2661        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2662        mContext.callerPermissions.remove(permission.MANAGE_USERS);
2663
2664        // System can retrieve the timestamp.
2665        mContext.binder.clearCallingIdentity();
2666        assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2667
2668        // Removing the device owner should clear the timestamp.
2669        clearDeviceOwner();
2670        assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
2671    }
2672
2673    public void testGetLastBugReportRequestTime() throws Exception {
2674        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2675        setupDeviceOwner();
2676        when(mContext.userManager.getUserCount()).thenReturn(1);
2677        mContext.packageName = admin1.getPackageName();
2678        mContext.applicationInfo = new ApplicationInfo();
2679        when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2680                .thenReturn(Color.WHITE);
2681        when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2682                anyObject())).thenReturn(Color.WHITE);
2683
2684        // No bug reports were requested so far.
2685        assertEquals(-1, dpm.getLastBugReportRequestTime());
2686
2687        // Requesting a bug report should update the timestamp.
2688        final long beforeRequest = System.currentTimeMillis();
2689        dpm.requestBugreport(admin1);
2690        final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
2691        final long afterRequest = System.currentTimeMillis();
2692        assertTrue(bugReportRequestTime >= beforeRequest);
2693        assertTrue(bugReportRequestTime <= afterRequest);
2694
2695        // Checking the timestamp again should not change it.
2696        Thread.sleep(2);
2697        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2698
2699        // Restarting the DPMS should not lose the timestamp.
2700        initializeDpms();
2701        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2702
2703        // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2704        mContext.binder.callingUid = 1234567;
2705        mContext.callerPermissions.add(permission.MANAGE_USERS);
2706        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2707        mContext.callerPermissions.remove(permission.MANAGE_USERS);
2708
2709        // System can retrieve the timestamp.
2710        mContext.binder.clearCallingIdentity();
2711        assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2712
2713        // Removing the device owner should clear the timestamp.
2714        clearDeviceOwner();
2715        assertEquals(-1, dpm.getLastBugReportRequestTime());
2716    }
2717
2718    public void testGetLastNetworkLogRetrievalTime() throws Exception {
2719        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2720        setupDeviceOwner();
2721        when(mContext.userManager.getUserCount()).thenReturn(1);
2722        when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2723                .thenReturn(true);
2724
2725        // No logs were retrieved so far.
2726        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
2727
2728        // Attempting to retrieve logs without enabling logging should not change the timestamp.
2729        dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2730        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
2731
2732        // Enabling logging should not change the timestamp.
2733        dpm.setNetworkLoggingEnabled(admin1, true);
2734        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
2735
2736        // Retrieving the logs should update the timestamp.
2737        final long beforeRetrieval = System.currentTimeMillis();
2738        dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2739        final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
2740        final long afterRetrieval = System.currentTimeMillis();
2741        assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2742        assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2743
2744        // Checking the timestamp again should not change it.
2745        Thread.sleep(2);
2746        assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2747
2748        // Retrieving the logs again should update the timestamp.
2749        dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2750        final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
2751        assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2752
2753        // Disabling logging should not change the timestamp.
2754        Thread.sleep(2);
2755        dpm.setNetworkLoggingEnabled(admin1, false);
2756        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2757
2758        // Restarting the DPMS should not lose the timestamp.
2759        initializeDpms();
2760        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2761
2762        // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2763        mContext.binder.callingUid = 1234567;
2764        mContext.callerPermissions.add(permission.MANAGE_USERS);
2765        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2766        mContext.callerPermissions.remove(permission.MANAGE_USERS);
2767
2768        // System can retrieve the timestamp.
2769        mContext.binder.clearCallingIdentity();
2770        assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2771
2772        // Removing the device owner should clear the timestamp.
2773        clearDeviceOwner();
2774        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
2775    }
2776
2777    public void testGetBindDeviceAdminTargetUsers() throws Exception {
2778        // Setup device owner.
2779        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2780        setupDeviceOwner();
2781
2782        // Only device owner is setup, the result list should be empty.
2783        List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2784        MoreAsserts.assertEmpty(targetUsers);
2785
2786        // Setup a managed profile managed by the same admin.
2787        final int MANAGED_PROFILE_USER_ID = 15;
2788        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2789        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2790
2791        // Add a secondary user, it should never talk with.
2792        final int ANOTHER_USER_ID = 36;
2793        mContext.addUser(ANOTHER_USER_ID, 0);
2794
2795        // Since the managed profile is not affiliated, they should not be allowed to talk to each
2796        // other.
2797        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2798        MoreAsserts.assertEmpty(targetUsers);
2799
2800        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2801        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2802        MoreAsserts.assertEmpty(targetUsers);
2803
2804        // Setting affiliation ids
2805        final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
2806        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2807        dpm.setAffiliationIds(admin1, userAffiliationIds);
2808
2809        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2810        dpm.setAffiliationIds(admin1, userAffiliationIds);
2811
2812        // Calling from device owner admin, the result list should just contain the managed
2813        // profile user id.
2814        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2815        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2816        MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2817
2818        // Calling from managed profile admin, the result list should just contain the system
2819        // user id.
2820        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2821        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2822        MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
2823
2824        // Changing affiliation ids in one
2825        dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
2826
2827        // Since the managed profile is not affiliated any more, they should not be allowed to talk
2828        // to each other.
2829        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2830        MoreAsserts.assertEmpty(targetUsers);
2831
2832        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2833        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2834        MoreAsserts.assertEmpty(targetUsers);
2835    }
2836
2837    public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2838        // Setup a device owner.
2839        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2840        setupDeviceOwner();
2841
2842        // Set up a managed profile managed by different package.
2843        final int MANAGED_PROFILE_USER_ID = 15;
2844        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2845        final ComponentName adminDifferentPackage =
2846                new ComponentName("another.package", "whatever.class");
2847        addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2848
2849        // Setting affiliation ids
2850        final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
2851        dpm.setAffiliationIds(admin1, userAffiliationIds);
2852
2853        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2854        dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
2855
2856        // Calling from device owner admin, we should get zero bind device admin target users as
2857        // their packages are different.
2858        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2859        List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2860        MoreAsserts.assertEmpty(targetUsers);
2861
2862        // Calling from managed profile admin, we should still get zero target users for the same
2863        // reason.
2864        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2865        targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2866        MoreAsserts.assertEmpty(targetUsers);
2867    }
2868
2869    public void testIsDeviceManaged() throws Exception {
2870        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2871        setupDeviceOwner();
2872
2873        // The device owner itself, any uid holding MANAGE_USERS permission and the system can
2874        // find out that the device has a device owner.
2875        assertTrue(dpm.isDeviceManaged());
2876        mContext.binder.callingUid = 1234567;
2877        mContext.callerPermissions.add(permission.MANAGE_USERS);
2878        assertTrue(dpm.isDeviceManaged());
2879        mContext.callerPermissions.remove(permission.MANAGE_USERS);
2880        mContext.binder.clearCallingIdentity();
2881        assertTrue(dpm.isDeviceManaged());
2882
2883        clearDeviceOwner();
2884
2885        // Any uid holding MANAGE_USERS permission and the system can find out that the device does
2886        // not have a device owner.
2887        mContext.binder.callingUid = 1234567;
2888        mContext.callerPermissions.add(permission.MANAGE_USERS);
2889        assertFalse(dpm.isDeviceManaged());
2890        mContext.callerPermissions.remove(permission.MANAGE_USERS);
2891        mContext.binder.clearCallingIdentity();
2892        assertFalse(dpm.isDeviceManaged());
2893    }
2894
2895    public void testDeviceOwnerOrganizationName() throws Exception {
2896        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2897        setupDeviceOwner();
2898
2899        dpm.setOrganizationName(admin1, "organization");
2900
2901        // Device owner can retrieve organization managing the device.
2902        assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2903
2904        // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
2905        mContext.binder.callingUid = 1234567;
2906        mContext.callerPermissions.add(permission.MANAGE_USERS);
2907        assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2908        mContext.callerPermissions.remove(permission.MANAGE_USERS);
2909
2910        // System can retrieve organization managing the device.
2911        mContext.binder.clearCallingIdentity();
2912        assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2913
2914        // Removing the device owner clears the organization managing the device.
2915        clearDeviceOwner();
2916        assertNull(dpm.getDeviceOwnerOrganizationName());
2917    }
2918
2919    private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2920        when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2921                userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2922        dpms.notifyChangeToContentObserver(
2923                Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2924    }
2925
2926    private void assertProvisioningAllowed(String action, boolean expected) {
2927        assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2928                dpm.isProvisioningAllowed(action));
2929    }
2930
2931    private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
2932        assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
2933    }
2934
2935    private void assertCheckProvisioningPreCondition(
2936            String action, String packageName, int provisioningCondition) {
2937        assertEquals("checkProvisioningPreCondition("
2938                        + action + ", " + packageName + ") returning unexpected result",
2939                provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
2940    }
2941
2942    /**
2943     * Setup a managed profile with the specified admin and its uid.
2944     * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
2945     * @param adminUid uid of the admin package.
2946     * @param copyFromAdmin package information for {@code admin} will be built based on this
2947     *     component's information.
2948     */
2949    private void addManagedProfile(
2950            ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
2951        final int userId = UserHandle.getUserId(adminUid);
2952        mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
2953        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2954        setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
2955        dpm.setActiveAdmin(admin, false, userId);
2956        assertTrue(dpm.setProfileOwner(admin, null, userId));
2957        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2958    }
2959}
2960