DevicePolicyManagerTest.java revision bf60f728cc7ed326fb8978afd9f589a685bb87b7
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 com.android.server.LocalServices;
19import com.android.server.SystemService;
20
21import android.Manifest.permission;
22import android.app.Activity;
23import android.app.admin.DeviceAdminReceiver;
24import android.app.admin.DevicePolicyManager;
25import android.app.admin.DevicePolicyManagerInternal;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.pm.PackageManager;
29import android.net.wifi.WifiInfo;
30import android.os.Build;
31import android.os.Build.VERSION_CODES;
32import android.os.Bundle;
33import android.os.Process;
34import android.os.UserHandle;
35import android.os.UserManager;
36import android.test.MoreAsserts;
37import android.util.Pair;
38
39import org.mockito.ArgumentCaptor;
40import org.mockito.invocation.InvocationOnMock;
41import org.mockito.stubbing.Answer;
42
43import java.util.ArrayList;
44import java.util.HashMap;
45import java.util.List;
46import java.util.Map;
47
48import static org.mockito.Matchers.any;
49import static org.mockito.Matchers.anyInt;
50import static org.mockito.Matchers.anyString;
51import static org.mockito.Matchers.eq;
52import static org.mockito.Matchers.isNull;
53import static org.mockito.Mockito.doAnswer;
54import static org.mockito.Mockito.doReturn;
55import static org.mockito.Mockito.reset;
56import static org.mockito.Mockito.times;
57import static org.mockito.Mockito.verify;
58import static org.mockito.Mockito.when;
59
60/**
61 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
62 *
63 m FrameworksServicesTests &&
64 adb install \
65   -r out/target/product/hammerhead/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
66 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
67   -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
68
69 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
70 */
71public class DevicePolicyManagerTest extends DpmTestBase {
72    private DpmMockContext mContext;
73    public DevicePolicyManager dpm;
74    public DevicePolicyManagerServiceTestable dpms;
75
76    @Override
77    protected void setUp() throws Exception {
78        super.setUp();
79
80        mContext = getContext();
81
82        when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
83                .thenReturn(true);
84
85        initializeDpms();
86
87        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
88        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
89        setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
90        setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
91
92        setUpUserManager();
93    }
94
95    private void initializeDpms() {
96        // Need clearCallingIdentity() to pass permission checks.
97        final long ident = mContext.binder.clearCallingIdentity();
98        try {
99            LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
100
101            dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
102
103            dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
104            dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
105
106            dpm = new DevicePolicyManagerTestable(mContext, dpms);
107        } finally {
108            mContext.binder.restoreCallingIdentity(ident);
109        }
110    }
111
112    private void setUpUserManager() {
113        // Emulate UserManager.set/getApplicationRestriction().
114        final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
115
116        // UM.setApplicationRestrictions() will save to appRestrictions.
117        doAnswer(new Answer<Void>() {
118            @Override
119            public Void answer(InvocationOnMock invocation) throws Throwable {
120                String pkg = (String) invocation.getArguments()[0];
121                Bundle bundle = (Bundle) invocation.getArguments()[1];
122                UserHandle user = (UserHandle) invocation.getArguments()[2];
123
124                appRestrictions.put(Pair.create(pkg, user), bundle);
125
126                return null;
127            }
128        }).when(mContext.userManager).setApplicationRestrictions(
129                anyString(), any(Bundle.class), any(UserHandle.class));
130
131        // UM.getApplicationRestrictions() will read from appRestrictions.
132        doAnswer(new Answer<Bundle>() {
133            @Override
134            public Bundle answer(InvocationOnMock invocation) throws Throwable {
135                String pkg = (String) invocation.getArguments()[0];
136                UserHandle user = (UserHandle) invocation.getArguments()[1];
137
138                return appRestrictions.get(Pair.create(pkg, user));
139            }
140        }).when(mContext.userManager).getApplicationRestrictions(
141                anyString(), any(UserHandle.class));
142
143        // Add the first secondary user.
144        mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
145    }
146
147    private void setAsProfileOwner(ComponentName admin) {
148        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
149        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
150
151        // PO needs to be an DA.
152        dpm.setActiveAdmin(admin, /* replace =*/ false);
153
154        // Fire!
155        assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
156
157        // Check
158        assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
159    }
160
161    public void testHasNoFeature() throws Exception {
162        when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
163                .thenReturn(false);
164
165        LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
166        new DevicePolicyManagerServiceTestable(mContext, dataDir);
167
168        // If the device has no DPMS feature, it shouldn't register the local service.
169        assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
170    }
171
172    /**
173     * Caller doesn't have proper permissions.
174     */
175    public void testSetActiveAdmin_SecurityException() {
176        // 1. Failure cases.
177
178        // Caller doesn't have MANAGE_DEVICE_ADMINS.
179        try {
180            dpm.setActiveAdmin(admin1, false);
181            fail("Didn't throw SecurityException");
182        } catch (SecurityException expected) {
183        }
184
185        // Caller has MANAGE_DEVICE_ADMINS, but for different user.
186        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
187        try {
188            dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
189            fail("Didn't throw SecurityException");
190        } catch (SecurityException expected) {
191        }
192    }
193
194    /**
195     * Test for:
196     * {@link DevicePolicyManager#setActiveAdmin}
197     *   with replace=false and replace=true
198     * {@link DevicePolicyManager#isAdminActive}
199     * {@link DevicePolicyManager#isAdminActiveAsUser}
200     * {@link DevicePolicyManager#getActiveAdmins}
201     * {@link DevicePolicyManager#getActiveAdminsAsUser}
202     */
203    public void testSetActiveAdmin() throws Exception {
204        // 1. Make sure the caller has proper permissions.
205        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
206
207        // 2. Call the API.
208        dpm.setActiveAdmin(admin1, /* replace =*/ false);
209
210        // 3. Verify internal calls.
211
212        // Check if the boradcast is sent.
213        verify(mContext.spiedContext).sendBroadcastAsUser(
214                MockUtils.checkIntentAction(
215                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
216                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
217        verify(mContext.spiedContext).sendBroadcastAsUser(
218                MockUtils.checkIntentAction(
219                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
220                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
221
222        verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
223                eq(admin1.getPackageName()),
224                eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
225                eq(PackageManager.DONT_KILL_APP),
226                eq(DpmMockContext.CALLER_USER_HANDLE),
227                anyString());
228
229        // TODO Verify other calls too.
230
231        // Make sure it's active admin1.
232        assertTrue(dpm.isAdminActive(admin1));
233        assertFalse(dpm.isAdminActive(admin2));
234        assertFalse(dpm.isAdminActive(admin3));
235
236        // But not admin1 for a different user.
237
238        // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
239        // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
240        mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
241
242        assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
243        assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
244
245        mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
246
247        // Next, add one more admin.
248        // Before doing so, update the application info, now it's enabled.
249        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
250                PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
251
252        dpm.setActiveAdmin(admin2, /* replace =*/ false);
253
254        // Now we have two admins.
255        assertTrue(dpm.isAdminActive(admin1));
256        assertTrue(dpm.isAdminActive(admin2));
257        assertFalse(dpm.isAdminActive(admin3));
258
259        // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
260        // again.  (times(1) because it was previously called for admin1)
261        verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
262                eq(admin1.getPackageName()),
263                eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
264                eq(PackageManager.DONT_KILL_APP),
265                eq(DpmMockContext.CALLER_USER_HANDLE),
266                anyString());
267
268        // 4. Add the same admin1 again without replace, which should throw.
269        try {
270            dpm.setActiveAdmin(admin1, /* replace =*/ false);
271            fail("Didn't throw");
272        } catch (IllegalArgumentException expected) {
273        }
274
275        // 5. Add the same admin1 again with replace, which should succeed.
276        dpm.setActiveAdmin(admin1, /* replace =*/ true);
277
278        // TODO make sure it's replaced.
279
280        // 6. Test getActiveAdmins()
281        List<ComponentName> admins = dpm.getActiveAdmins();
282        assertEquals(2, admins.size());
283        assertEquals(admin1, admins.get(0));
284        assertEquals(admin2, admins.get(1));
285
286        // Another user has no admins.
287        mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
288
289        assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
290                dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
291
292        mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
293    }
294
295    public void testSetActiveAdmin_multiUsers() throws Exception {
296
297        final int ANOTHER_USER_ID = 100;
298        final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
299
300        mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
301
302        // Set up pacakge manager for the other user.
303        setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
304
305        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
306
307        dpm.setActiveAdmin(admin1, /* replace =*/ false);
308
309        mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
310        dpm.setActiveAdmin(admin2, /* replace =*/ false);
311
312
313        mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
314        assertTrue(dpm.isAdminActive(admin1));
315        assertFalse(dpm.isAdminActive(admin2));
316
317        mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
318        assertFalse(dpm.isAdminActive(admin1));
319        assertTrue(dpm.isAdminActive(admin2));
320    }
321
322    /**
323     * Test for:
324     * {@link DevicePolicyManager#setActiveAdmin}
325     *   with replace=false
326     */
327    public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
328        // 1. Make sure the caller has proper permissions.
329        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
330
331        dpm.setActiveAdmin(admin1, /* replace =*/ false);
332        assertTrue(dpm.isAdminActive(admin1));
333
334        // Add the same admin1 again without replace, which should throw.
335        try {
336            dpm.setActiveAdmin(admin1, /* replace =*/ false);
337            fail("Didn't throw");
338        } catch (IllegalArgumentException expected) {
339        }
340    }
341
342    /**
343     * Test for:
344     * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
345     * BIND_DEVICE_ADMIN.
346     */
347    public void testSetActiveAdmin_permissionCheck() throws Exception {
348        // 1. Make sure the caller has proper permissions.
349        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
350
351        try {
352            dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
353            fail();
354        } catch (IllegalArgumentException expected) {
355            assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
356        }
357        assertFalse(dpm.isAdminActive(adminNoPerm));
358
359        // Change the target API level to MNC.  Now it can be set as DA.
360        setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
361                VERSION_CODES.M);
362        dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
363        assertTrue(dpm.isAdminActive(adminNoPerm));
364
365        // TODO Test the "load from the file" case where DA will still be loaded even without
366        // BIND_DEVICE_ADMIN and target API is N.
367    }
368
369    /**
370     * Test for:
371     * {@link DevicePolicyManager#removeActiveAdmin}
372     */
373    public void testRemoveActiveAdmin_SecurityException() {
374        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
375
376        // Add admin.
377
378        dpm.setActiveAdmin(admin1, /* replace =*/ false);
379
380        assertTrue(dpm.isAdminActive(admin1));
381
382        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
383
384        // Directly call the DPMS method with a different userid, which should fail.
385        try {
386            dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
387            fail("Didn't throw SecurityException");
388        } catch (SecurityException expected) {
389        }
390
391        // Try to remove active admin with a different caller userid should fail too, without
392        // having MANAGE_DEVICE_ADMINS.
393        mContext.callerPermissions.clear();
394
395        // Change the caller, and call into DPMS directly with a different user-id.
396
397        mContext.binder.callingUid = 1234567;
398        try {
399            dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
400            fail("Didn't throw SecurityException");
401        } catch (SecurityException expected) {
402        }
403    }
404
405    /**
406     * Test for:
407     * {@link DevicePolicyManager#removeActiveAdmin}
408     */
409    public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
410        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
411
412        // Add admin1.
413
414        dpm.setActiveAdmin(admin1, /* replace =*/ false);
415
416        assertTrue(dpm.isAdminActive(admin1));
417        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
418
419        // Different user, but should work, because caller has proper permissions.
420        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
421
422        // Change the caller, and call into DPMS directly with a different user-id.
423        mContext.binder.callingUid = 1234567;
424
425        dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
426
427        assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
428
429        // TODO DO Still can't be removed in this case.
430    }
431
432    /**
433     * Test for:
434     * {@link DevicePolicyManager#removeActiveAdmin}
435     */
436    public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
437        // Need MANAGE_DEVICE_ADMINS for setActiveAdmin.  We'll remove it later.
438        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
439
440        // Add admin1.
441
442        dpm.setActiveAdmin(admin1, /* replace =*/ false);
443
444        assertTrue(dpm.isAdminActive(admin1));
445        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
446
447        // Broadcast from saveSettingsLocked().
448        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
449                MockUtils.checkIntentAction(
450                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
451                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
452
453        // Remove.  No permissions, but same user, so it'll work.
454        mContext.callerPermissions.clear();
455        dpm.removeActiveAdmin(admin1);
456
457        final ArgumentCaptor<BroadcastReceiver> brCap =
458                ArgumentCaptor.forClass(BroadcastReceiver.class);
459
460        // Is removing now, but not removed yet.
461        assertTrue(dpm.isAdminActive(admin1));
462        assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
463
464        verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
465                MockUtils.checkIntentAction(
466                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
467                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
468                isNull(String.class),
469                brCap.capture(),
470                eq(dpms.mHandler),
471                eq(Activity.RESULT_OK),
472                isNull(String.class),
473                isNull(Bundle.class));
474
475        brCap.getValue().onReceive(mContext, null);
476
477        assertFalse(dpm.isAdminActive(admin1));
478        assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
479
480        // Again broadcast from saveSettingsLocked().
481        verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
482                MockUtils.checkIntentAction(
483                        DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
484                MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
485
486        // TODO Check other internal calls.
487    }
488
489    /**
490     * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs
491     * successfully.
492     */
493    public void testSetDeviceOwner() throws Exception {
494        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
495        mContext.callerPermissions.add(permission.MANAGE_USERS);
496        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
497        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
498
499        // In this test, change the caller user to "system".
500        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
501
502        // Make sure admin1 is installed on system user.
503        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
504
505        // Check various get APIs.
506        checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
507
508        // DO needs to be an DA.
509        dpm.setActiveAdmin(admin1, /* replace =*/ false);
510
511        // Fire!
512        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
513
514        // getDeviceOwnerComponent should return the admin1 component.
515        assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
516        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
517
518        // Check various get APIs.
519        checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
520
521        // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
522        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
523        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
524        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
525
526        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
527
528        // Verify internal calls.
529        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
530                eq(admin1.getPackageName()));
531
532        // TODO We should check if the caller has called clearCallerIdentity().
533        verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
534                eq(UserHandle.USER_SYSTEM), eq(false));
535
536        verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
537                MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
538                MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
539
540        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
541
542        // Try to set a profile owner on the same user, which should fail.
543        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
544        dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
545        try {
546            dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
547            fail("IllegalStateException not thrown");
548        } catch (IllegalStateException expected) {
549            assertTrue("Message was: " + expected.getMessage(),
550                    expected.getMessage().contains("already has a device owner"));
551        }
552
553        // TODO Test getDeviceOwnerName() too.  To do so, we need to change
554        // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
555    }
556
557    private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
558        final int origCallingUser = mContext.binder.callingUid;
559        final List origPermissions = new ArrayList(mContext.callerPermissions);
560        mContext.callerPermissions.clear();
561
562        mContext.callerPermissions.add(permission.MANAGE_USERS);
563
564        mContext.binder.callingUid = Process.SYSTEM_UID;
565
566        // TODO Test getDeviceOwnerName() too.  To do so, we need to change
567        // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
568        if (hasDeviceOwner) {
569            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
570            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
571            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
572
573            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
574            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
575            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
576        } else {
577            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
578            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
579            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
580
581            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
582            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
583            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
584        }
585
586        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
587        if (hasDeviceOwner) {
588            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
589            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
590            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
591
592            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
593            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
594            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
595        } else {
596            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
597            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
598            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
599
600            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
601            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
602            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
603        }
604
605        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
606        // Still with MANAGE_USERS.
607        assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
608        assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
609        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
610
611        if (hasDeviceOwner) {
612            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
613            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
614            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
615        } else {
616            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
617            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
618            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
619        }
620
621        mContext.binder.callingUid = Process.SYSTEM_UID;
622        mContext.callerPermissions.remove(permission.MANAGE_USERS);
623        // System can still call "OnAnyUser" without MANAGE_USERS.
624        if (hasDeviceOwner) {
625            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
626            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
627            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
628
629            assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
630            assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
631            assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
632        } else {
633            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
634            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
635            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
636
637            assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
638            assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
639            assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
640        }
641
642        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
643        // Still no MANAGE_USERS.
644        if (hasDeviceOwner) {
645            assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
646            assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
647            assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
648        } else {
649            assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
650            assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
651            assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
652        }
653
654        try {
655            dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
656            fail();
657        } catch (SecurityException expected) {
658        }
659        try {
660            dpm.getDeviceOwnerComponentOnAnyUser();
661            fail();
662        } catch (SecurityException expected) {
663        }
664        try {
665            dpm.getDeviceOwnerUserId();
666            fail();
667        } catch (SecurityException expected) {
668        }
669        try {
670            dpm.getDeviceOwnerNameOnAnyUser();
671            fail();
672        } catch (SecurityException expected) {
673        }
674
675        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
676        // Still no MANAGE_USERS.
677        assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
678        assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
679        assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
680
681        try {
682            dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
683            fail();
684        } catch (SecurityException expected) {
685        }
686        try {
687            dpm.getDeviceOwnerComponentOnAnyUser();
688            fail();
689        } catch (SecurityException expected) {
690        }
691        try {
692            dpm.getDeviceOwnerUserId();
693            fail();
694        } catch (SecurityException expected) {
695        }
696        try {
697            dpm.getDeviceOwnerNameOnAnyUser();
698            fail();
699        } catch (SecurityException expected) {
700        }
701
702        // Restore.
703        mContext.binder.callingUid = origCallingUser;
704        mContext.callerPermissions.addAll(origPermissions);
705    }
706
707
708    /**
709     * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
710     */
711    public void testSetDeviceOwner_noSuchPackage() {
712        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
713        mContext.callerPermissions.add(permission.MANAGE_USERS);
714        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
715        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
716
717        // Call from a process on the system user.
718        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
719
720        try {
721            dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
722            fail("Didn't throw IllegalArgumentException");
723        } catch (IllegalArgumentException expected) {
724            assertTrue("Message was: " + expected.getMessage(),
725                    expected.getMessage().contains("Invalid component"));
726        }
727    }
728
729    public void testSetDeviceOwner_failures() throws Exception {
730        // TODO Test more failure cases.  Basically test all chacks in enforceCanSetDeviceOwner().
731    }
732
733    public void testClearDeviceOwner() throws Exception {
734        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
735        mContext.callerPermissions.add(permission.MANAGE_USERS);
736        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
737        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
738
739        // Set admin1 as a DA to the secondary user.
740        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
741
742        dpm.setActiveAdmin(admin1, /* replace =*/ false);
743
744        // Set admin 1 as the DO to the system user.
745
746        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
747        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
748        dpm.setActiveAdmin(admin1, /* replace =*/ false);
749        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
750
751        // Verify internal calls.
752        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
753                eq(admin1.getPackageName()));
754
755        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
756
757        // Set up other mocks.
758        when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
759
760        // Now call clear.
761        doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUid(
762                eq(admin1.getPackageName()),
763                anyInt());
764        dpm.clearDeviceOwnerApp(admin1.getPackageName());
765
766        // Now DO shouldn't be set.
767        assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
768
769        // TODO Check other calls.
770    }
771
772    public void testClearDeviceOwner_fromDifferentUser() throws Exception {
773        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
774        mContext.callerPermissions.add(permission.MANAGE_USERS);
775        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
776        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
777
778        // Set admin1 as a DA to the secondary user.
779        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
780
781        dpm.setActiveAdmin(admin1, /* replace =*/ false);
782
783        // Set admin 1 as the DO to the system user.
784
785        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
786        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
787        dpm.setActiveAdmin(admin1, /* replace =*/ false);
788        assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
789
790        // Verify internal calls.
791        verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
792                eq(admin1.getPackageName()));
793
794        assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
795
796        // Now call clear from the secondary user, which should throw.
797        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
798
799        // Now call clear.
800        doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUid(
801                eq(admin1.getPackageName()),
802                anyInt());
803        try {
804            dpm.clearDeviceOwnerApp(admin1.getPackageName());
805            fail("Didn't throw");
806        } catch (SecurityException e) {
807            assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
808        }
809
810        // DO shouldn't be removed.
811        assertTrue(dpm.isDeviceManaged());
812    }
813
814    public void testSetProfileOwner() throws Exception {
815        setAsProfileOwner(admin1);
816
817        // Try setting DO on the same user, which should fail.
818        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
819        dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
820        try {
821            dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
822            fail("IllegalStateException not thrown");
823        } catch (IllegalStateException expected) {
824            assertTrue("Message was: " + expected.getMessage(),
825                    expected.getMessage().contains("already has a profile owner"));
826        }
827    }
828
829    public void testSetProfileOwner_failures() throws Exception {
830        // TODO Test more failure cases.  Basically test all chacks in enforceCanSetProfileOwner().
831    }
832
833    public void testGetDeviceOwnerAdminLocked() throws Exception {
834        checkDeviceOwnerWithMultipleDeviceAdmins();
835    }
836
837    private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
838        // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
839        // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
840        // make sure it gets the right component from the right user.
841
842        final int ANOTHER_USER_ID = 100;
843        final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
844
845        mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
846
847        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
848        mContext.callerPermissions.add(permission.MANAGE_USERS);
849        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
850        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
851
852        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
853
854        // Make sure the admin packge is installed to each user.
855        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
856        setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
857
858        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
859        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
860
861        setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
862
863
864        // Set active admins to the users.
865        dpm.setActiveAdmin(admin1, /* replace =*/ false);
866        dpm.setActiveAdmin(admin3, /* replace =*/ false);
867
868        dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
869        dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
870
871        dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
872
873        // Set DO on the first non-system user.
874        mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
875        assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
876
877        assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
878
879        // Then check getDeviceOwnerAdminLocked().
880        assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
881        assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
882    }
883
884    /**
885     * This essentially tests
886     * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is private.)
887     *
888     * We didn't use to persist the DO component class name, but now we do, and the above method
889     * finds the right component from a package name upon migration.
890     */
891    public void testDeviceOwnerMigration() throws Exception {
892        checkDeviceOwnerWithMultipleDeviceAdmins();
893
894        // Overwrite the device owner setting and clears the clas name.
895        dpms.mOwners.setDeviceOwner(
896                new ComponentName(admin2.getPackageName(), ""),
897                "owner-name", DpmMockContext.CALLER_USER_HANDLE);
898        dpms.mOwners.writeDeviceOwner();
899
900        // Make sure the DO component name doesn't have a class name.
901        assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
902
903        // Then create a new DPMS to have it load the settings from files.
904        when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
905                .thenReturn(new Bundle());
906        initializeDpms();
907
908        // Now the DO component name is a full name.
909        // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
910        // DO.
911        assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
912    }
913
914    public void testSetGetApplicationRestriction() {
915        setAsProfileOwner(admin1);
916
917        {
918            Bundle rest = new Bundle();
919            rest.putString("KEY_STRING", "Foo1");
920            dpm.setApplicationRestrictions(admin1, "pkg1", rest);
921        }
922
923        {
924            Bundle rest = new Bundle();
925            rest.putString("KEY_STRING", "Foo2");
926            dpm.setApplicationRestrictions(admin1, "pkg2", rest);
927        }
928
929        {
930            Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
931            assertNotNull(returned);
932            assertEquals(returned.size(), 1);
933            assertEquals(returned.get("KEY_STRING"), "Foo1");
934        }
935
936        {
937            Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
938            assertNotNull(returned);
939            assertEquals(returned.size(), 1);
940            assertEquals(returned.get("KEY_STRING"), "Foo2");
941        }
942
943        dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
944        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
945    }
946
947    public void testApplicationRestrictionsManagingApp() throws Exception {
948        setAsProfileOwner(admin1);
949
950        final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
951        final int appRestrictionsManagerAppId = 20987;
952        final int appRestrictionsManagerUid = UserHandle.getUid(
953                DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
954        doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUid(
955                eq(appRestrictionsManagerPackage),
956                eq(DpmMockContext.CALLER_USER_HANDLE));
957        mContext.binder.callingUid = appRestrictionsManagerUid;
958
959        // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
960        // delegated that permission yet.
961        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
962        Bundle rest = new Bundle();
963        rest.putString("KEY_STRING", "Foo1");
964        try {
965            dpm.setApplicationRestrictions(null, "pkg1", rest);
966            fail("Didn't throw expected SecurityException");
967        } catch (SecurityException expected) {
968            MoreAsserts.assertContainsRegex(
969                    "caller cannot manage application restrictions", expected.getMessage());
970        }
971        try {
972            dpm.getApplicationRestrictions(null, "pkg1");
973            fail("Didn't throw expected SecurityException");
974        } catch (SecurityException expected) {
975            MoreAsserts.assertContainsRegex(
976                    "caller cannot manage application restrictions", expected.getMessage());
977        }
978
979        // Check via the profile owner that no restrictions were set.
980        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
981        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
982
983        // Let appRestrictionsManagerPackage manage app restrictions
984        dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
985        assertEquals(appRestrictionsManagerPackage,
986                dpm.getApplicationRestrictionsManagingPackage(admin1));
987
988        // Now that package should be able to set and retrieve app restrictions.
989        mContext.binder.callingUid = appRestrictionsManagerUid;
990        assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
991        dpm.setApplicationRestrictions(null, "pkg1", rest);
992        Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
993        assertEquals(1, returned.size(), 1);
994        assertEquals("Foo1", returned.get("KEY_STRING"));
995
996        // The same app running on a separate user shouldn't be able to manage app restrictions.
997        mContext.binder.callingUid = UserHandle.getUid(
998                UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
999        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1000        try {
1001            dpm.setApplicationRestrictions(null, "pkg1", rest);
1002            fail("Didn't throw expected SecurityException");
1003        } catch (SecurityException expected) {
1004            MoreAsserts.assertContainsRegex(
1005                    "caller cannot manage application restrictions", expected.getMessage());
1006        }
1007
1008        // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1009        // too.
1010        mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1011        assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1012        dpm.setApplicationRestrictions(admin1, "pkg1", null);
1013        assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1014
1015        // Removing the ability for the package to manage app restrictions.
1016        dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1017        assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1018        mContext.binder.callingUid = appRestrictionsManagerUid;
1019        assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1020        try {
1021            dpm.setApplicationRestrictions(null, "pkg1", null);
1022            fail("Didn't throw expected SecurityException");
1023        } catch (SecurityException expected) {
1024            MoreAsserts.assertContainsRegex(
1025                    "caller cannot manage application restrictions", expected.getMessage());
1026        }
1027    }
1028
1029    public void testSetUserRestriction_asDo() throws Exception {
1030        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1031        mContext.callerPermissions.add(permission.MANAGE_USERS);
1032        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1033        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1034
1035        // First, set DO.
1036
1037        // Call from a process on the system user.
1038        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1039
1040        // Make sure admin1 is installed on system user.
1041        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1042
1043        // Call.
1044        dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1045        assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1046                UserHandle.USER_SYSTEM));
1047
1048        DpmTestUtils.assertRestrictions(
1049                DpmTestUtils.newRestrictions(),
1050                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1051        );
1052        DpmTestUtils.assertRestrictions(
1053                DpmTestUtils.newRestrictions(),
1054                dpm.getUserRestrictions(admin1)
1055        );
1056
1057        reset(mContext.userManagerInternal);
1058
1059        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1060        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1061                eq(UserHandle.USER_SYSTEM),
1062                MockUtils.checkUserRestrictions(),
1063                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1064                );
1065        reset(mContext.userManagerInternal);
1066
1067        dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1068        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1069                eq(UserHandle.USER_SYSTEM),
1070                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1071                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1072        );
1073        reset(mContext.userManagerInternal);
1074
1075        DpmTestUtils.assertRestrictions(
1076                DpmTestUtils.newRestrictions(
1077                        UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1078                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1079        );
1080        DpmTestUtils.assertRestrictions(
1081                DpmTestUtils.newRestrictions(
1082                        UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1083                dpm.getUserRestrictions(admin1)
1084        );
1085
1086        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1087        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1088                eq(UserHandle.USER_SYSTEM),
1089                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1090                MockUtils.checkUserRestrictions()
1091        );
1092        reset(mContext.userManagerInternal);
1093
1094        DpmTestUtils.assertRestrictions(
1095                DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1096                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1097        );
1098        DpmTestUtils.assertRestrictions(
1099                DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1100                dpm.getUserRestrictions(admin1)
1101        );
1102
1103        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1104        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1105                eq(UserHandle.USER_SYSTEM),
1106                MockUtils.checkUserRestrictions(),
1107                MockUtils.checkUserRestrictions()
1108        );
1109        reset(mContext.userManagerInternal);
1110
1111        DpmTestUtils.assertRestrictions(
1112                DpmTestUtils.newRestrictions(),
1113                dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1114        );
1115        DpmTestUtils.assertRestrictions(
1116                DpmTestUtils.newRestrictions(),
1117                dpm.getUserRestrictions(admin1)
1118        );
1119
1120        // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1121        // DO sets them, the scope is global.
1122        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1123        reset(mContext.userManagerInternal);
1124        dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1125        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1126                eq(UserHandle.USER_SYSTEM),
1127                MockUtils.checkUserRestrictions(),
1128                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1129                        UserManager.DISALLOW_UNMUTE_MICROPHONE)
1130        );
1131        reset(mContext.userManagerInternal);
1132
1133        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1134        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1135
1136
1137        // More tests.
1138        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1139        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1140                eq(UserHandle.USER_SYSTEM),
1141                MockUtils.checkUserRestrictions(),
1142                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1143        );
1144        reset(mContext.userManagerInternal);
1145
1146        dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1147        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1148                eq(UserHandle.USER_SYSTEM),
1149                MockUtils.checkUserRestrictions(),
1150                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1151                        UserManager.DISALLOW_ADD_USER)
1152        );
1153        reset(mContext.userManagerInternal);
1154
1155        dpm.setCameraDisabled(admin1, true);
1156        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1157                eq(UserHandle.USER_SYSTEM),
1158                // DISALLOW_CAMERA will be applied to both local and global.
1159                MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1160                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1161                        UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1162        );
1163        reset(mContext.userManagerInternal);
1164
1165        // Set up another DA and let it disable camera.  Now DISALLOW_CAMERA will only be applied
1166        // locally.
1167        dpm.setCameraDisabled(admin1, false);
1168        reset(mContext.userManagerInternal);
1169
1170        setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1171        dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1172        dpm.setCameraDisabled(admin2, true);
1173
1174        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1175                eq(UserHandle.USER_SYSTEM),
1176                // DISALLOW_CAMERA will be applied to both local and global.
1177                MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1178                MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1179                        UserManager.DISALLOW_ADD_USER)
1180        );
1181        reset(mContext.userManagerInternal);
1182        // TODO Make sure restrictions are written to the file.
1183    }
1184
1185    public void testSetUserRestriction_asPo() {
1186        setAsProfileOwner(admin1);
1187
1188        DpmTestUtils.assertRestrictions(
1189                DpmTestUtils.newRestrictions(),
1190                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1191                        .ensureUserRestrictions()
1192        );
1193
1194        dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1195        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1196                eq(DpmMockContext.CALLER_USER_HANDLE),
1197                MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1198                isNull(Bundle.class)
1199        );
1200        reset(mContext.userManagerInternal);
1201
1202        dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1203        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1204                eq(DpmMockContext.CALLER_USER_HANDLE),
1205                MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1206                        UserManager.DISALLOW_OUTGOING_CALLS),
1207                isNull(Bundle.class)
1208        );
1209        reset(mContext.userManagerInternal);
1210
1211        DpmTestUtils.assertRestrictions(
1212                DpmTestUtils.newRestrictions(
1213                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1214                        UserManager.DISALLOW_OUTGOING_CALLS
1215                ),
1216                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1217                        .ensureUserRestrictions()
1218        );
1219        DpmTestUtils.assertRestrictions(
1220                DpmTestUtils.newRestrictions(
1221                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1222                        UserManager.DISALLOW_OUTGOING_CALLS
1223                ),
1224                dpm.getUserRestrictions(admin1)
1225        );
1226
1227        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1228        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1229                eq(DpmMockContext.CALLER_USER_HANDLE),
1230                MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1231                isNull(Bundle.class)
1232        );
1233        reset(mContext.userManagerInternal);
1234
1235        DpmTestUtils.assertRestrictions(
1236                DpmTestUtils.newRestrictions(
1237                        UserManager.DISALLOW_OUTGOING_CALLS
1238                ),
1239                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1240                        .ensureUserRestrictions()
1241        );
1242        DpmTestUtils.assertRestrictions(
1243                DpmTestUtils.newRestrictions(
1244                        UserManager.DISALLOW_OUTGOING_CALLS
1245                ),
1246                dpm.getUserRestrictions(admin1)
1247        );
1248
1249        dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1250        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1251                eq(DpmMockContext.CALLER_USER_HANDLE),
1252                MockUtils.checkUserRestrictions(),
1253                isNull(Bundle.class)
1254        );
1255        reset(mContext.userManagerInternal);
1256
1257        DpmTestUtils.assertRestrictions(
1258                DpmTestUtils.newRestrictions(),
1259                dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1260                        .ensureUserRestrictions()
1261        );
1262        DpmTestUtils.assertRestrictions(
1263                DpmTestUtils.newRestrictions(),
1264                dpm.getUserRestrictions(admin1)
1265        );
1266
1267        // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1268        // though when DO sets them they'll be applied globally.
1269        dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1270        reset(mContext.userManagerInternal);
1271        dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1272        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1273                eq(DpmMockContext.CALLER_USER_HANDLE),
1274                MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1275                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1276                isNull(Bundle.class)
1277        );
1278        reset(mContext.userManagerInternal);
1279
1280        dpm.setCameraDisabled(admin1, true);
1281        verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1282                eq(DpmMockContext.CALLER_USER_HANDLE),
1283                MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1284                        UserManager.DISALLOW_ADJUST_VOLUME,
1285                        UserManager.DISALLOW_UNMUTE_MICROPHONE),
1286                isNull(Bundle.class)
1287        );
1288        reset(mContext.userManagerInternal);
1289
1290        // TODO Make sure restrictions are written to the file.
1291    }
1292
1293    public void testGetMacAddress() throws Exception {
1294        mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1295        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1296        mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1297
1298        // In this test, change the caller user to "system".
1299        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1300
1301        // Make sure admin1 is installed on system user.
1302        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1303
1304        // Test 1. Caller doesn't have DO or DA.
1305        try {
1306            dpm.getWifiMacAddress();
1307            fail();
1308        } catch (SecurityException e) {
1309            MoreAsserts.assertContainsRegex("No active admin owned", e.getMessage());
1310        }
1311
1312        // DO needs to be an DA.
1313        dpm.setActiveAdmin(admin1, /* replace =*/ false);
1314        assertTrue(dpm.isAdminActive(admin1));
1315
1316        // Test 2. Caller has DA, but not DO.
1317        try {
1318            dpm.getWifiMacAddress();
1319            fail();
1320        } catch (SecurityException e) {
1321            MoreAsserts.assertContainsRegex("No active admin owned", e.getMessage());
1322        }
1323
1324        // Test 3. Caller has PO, but not DO.
1325        assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1326        try {
1327            dpm.getWifiMacAddress();
1328            fail();
1329        } catch (SecurityException e) {
1330            MoreAsserts.assertContainsRegex("No active admin owned", e.getMessage());
1331        }
1332
1333        // Remove PO.
1334        dpm.clearProfileOwner(admin1);
1335
1336        // Test 4, Caller is DO now.
1337        assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1338
1339        // 4-1.  But no WifiInfo.
1340        assertNull(dpm.getWifiMacAddress());
1341
1342        // 4-2.  Returns WifiInfo, but with the default MAC.
1343        when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
1344        assertNull(dpm.getWifiMacAddress());
1345
1346        // 4-3. With a real MAC address.
1347        final WifiInfo wi = new WifiInfo();
1348        wi.setMacAddress("11:22:33:44:55:66");
1349        when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
1350        assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress());
1351    }
1352}
1353