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