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