Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 2f26b79e authored by Tony Mak's avatar Tony Mak
Browse files

Unit test for getBindDeviceAdminTargetUsers

Was meant to write test for bindDeviceAdminServiceAsUser, but
it can't be done without having tests for
getBindDeviceAdminTargetUsers first as bindDeviceAdminService depends
on getBindDeviceAdminTargetUsers.

A bit shocked by we didn't have any managed profile tests in
DevicePolicyManagerTest. Added managed profile support in the CL.

Bug: 32764274

Test: runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java

Change-Id: If412e4f44c3ae998f69e17411f2503a97f80149f
parent d0835e45
Loading
Loading
Loading
Loading
+1 −2
Original line number Diff line number Diff line
@@ -9608,8 +9608,7 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
            final long callingIdentity = mInjector.binderClearCallingIdentity();
            try {
                String callingOwnerPackage = callingOwner.info.getComponent().getPackageName();
                for (int userId : mUserManager.getProfileIds(
                        callingUserId, /* enabledOnly= */ false)) {
                for (int userId : mUserManager.getProfileIdsWithDisabled(callingUserId)) {
                    if (userId == callingUserId) {
                        continue;
                    }
+77 −0
Original line number Diff line number Diff line
@@ -22,15 +22,20 @@ import android.app.admin.DevicePolicyManager;
import android.app.admin.DevicePolicyManagerInternal;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.IIpConnectivityMetrics;
import android.content.pm.UserInfo;
import android.net.wifi.WifiInfo;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
@@ -2447,6 +2452,60 @@ public class DevicePolicyManagerTest extends DpmTestBase {
        assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
    }

    public void testGetBindDeviceAdminTargetUsers() throws Exception {
        // Setup device owner.
        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
        setupDeviceOwner();

        // Only device owner is setup, the result list should be empty.
        List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
        MoreAsserts.assertEmpty(targetUsers);

        // Setup a managed profile managed by the same admin.
        final int MANAGED_PROFILE_USER_ID = 15;
        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
        addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);

        // Add a secondary user, it should never talk with.
        final int ANOTHER_USER_ID = 36;
        mContext.addUser(ANOTHER_USER_ID, 0);

        // Calling from device owner admin, the result list should just contain the managed
        // profile user id.
        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
        MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));

        // Calling from managed profile admin, the result list should just contain the system
        // user id.
        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
        targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
        MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
    }

    public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
        // Setup a device owner.
        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
        setupDeviceOwner();

        // Set up a managed profile managed by different package.
        final int MANAGED_PROFILE_USER_ID = 15;
        final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
        final ComponentName adminDifferentPackage =
                new ComponentName("another.package", "whatever.class");
        addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);

        // Calling from device owner admin, we should get zero bind device admin target users as
        // their packages are different.
        List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
        MoreAsserts.assertEmpty(targetUsers);

        // Calling from managed profile admin, we should still get zero target users for the same
        // reason.
        mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
        targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
        MoreAsserts.assertEmpty(targetUsers);
    }

    private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
        when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
                userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
@@ -2458,4 +2517,22 @@ public class DevicePolicyManagerTest extends DpmTestBase {
        assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
                dpm.isProvisioningAllowed(action));
    }

    /**
     * Setup a managed profile with the specified admin and its uid.
     * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
     * @param adminUid uid of the admin package.
     * @param copyFromAdmin package information for {@code admin} will be built based on this
     *     component's information.
     */
    private void addManagedProfile(
            ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
        final int userId = UserHandle.getUserId(adminUid);
        mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
        mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
        setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
        dpm.setActiveAdmin(admin, false, userId);
        assertTrue(dpm.setProfileOwner(admin, null, userId));
        mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
    }
}
+21 −18
Original line number Diff line number Diff line
@@ -16,8 +16,6 @@

package com.android.server.devicepolicy;

import com.android.internal.widget.LockPatternUtils;

import android.app.IActivityManager;
import android.app.NotificationManager;
import android.app.backup.IBackupManager;
@@ -47,6 +45,8 @@ import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
import android.view.IWindowManager;

import com.android.internal.widget.LockPatternUtils;

import org.junit.Assert;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -324,16 +324,21 @@ public class DpmMockContext extends MockContext {
        contentResolver = new MockContentResolver();

        // Add the system user
        systemUserDataDir = addUser(UserHandle.USER_SYSTEM, UserInfo.FLAG_PRIMARY);
        systemUserDataDir =
                addUser(UserHandle.USER_SYSTEM, UserInfo.FLAG_PRIMARY, UserHandle.USER_SYSTEM);

        // System user is always running.
        setUserRunning(UserHandle.USER_SYSTEM, true);
    }

    public File addUser(int userId, int flags) {
        return addUser(userId, flags, UserInfo.NO_PROFILE_GROUP_ID);
    }

    public File addUser(int userId, int flags, int profileGroupId) {
        // Set up (default) UserInfo for CALLER_USER_HANDLE.
        final UserInfo uh = new UserInfo(userId, "user" + userId, flags);
        uh.profileGroupId = profileGroupId;
        when(userManager.getUserInfo(eq(userId))).thenReturn(uh);

        mUserInfos.add(uh);
@@ -345,12 +350,7 @@ public class DpmMockContext extends MockContext {
                    @Override
                    public UserInfo answer(InvocationOnMock invocation) throws Throwable {
                        final int userId = (int) invocation.getArguments()[0];
                        for (UserInfo ui : mUserInfos) {
                            if (ui.id == userId) {
                                return ui;
                            }
                        }
                        return null;
                        return getUserInfo(userId);
                    }
                }
        );
@@ -369,16 +369,13 @@ public class DpmMockContext extends MockContext {
                    public int[] answer(InvocationOnMock invocation) throws Throwable {
                        final int userId = (int) invocation.getArguments()[0];
                        List<UserInfo> profiles = getProfiles(userId);
                        int[] results = new int[profiles.size()];
                        for (int i = 0; i < results.length; i++) {
                            results[i] = profiles.get(i).id;
                        }
                        return results;
                        return profiles.stream()
                                .mapToInt(profile -> profile.id)
                                .toArray();
                    }
                }
        );


        // Create a data directory.
        final File dir = new File(dataDir, "user" + userId);
        DpmTestUtils.clearDir(dir);
@@ -387,6 +384,15 @@ public class DpmMockContext extends MockContext {
        return dir;
    }

    private UserInfo getUserInfo(int userId) {
        for (UserInfo ui : mUserInfos) {
            if (ui.id == userId) {
                return ui;
            }
        }
        return null;
    }

    private List<UserInfo> getProfiles(int userId) {
        final ArrayList<UserInfo> ret = new ArrayList<UserInfo>();
        UserInfo parent = null;
@@ -401,9 +407,6 @@ public class DpmMockContext extends MockContext {
        }
        ret.add(parent);
        for (UserInfo ui : mUserInfos) {
            if (ui.id == userId) {
                continue;
            }
            if (ui.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
                    && ui.profileGroupId == parent.profileGroupId) {
                ret.add(ui);
+7 −1
Original line number Diff line number Diff line
@@ -101,6 +101,13 @@ public abstract class DpmTestBase extends AndroidTestCase {
                admin);
    }

    protected void setUpPackageManagerForFakeAdmin(ComponentName admin, int packageUid,
            ComponentName copyFromAdmin)
            throws Exception {
        setUpPackageManagerForFakeAdmin(admin, packageUid,
                /* enabledSetting =*/ null, /* appTargetSdk = */ null, copyFromAdmin);
    }

    /**
     * Set up a component in the mock package manager to be an active admin.
     *
@@ -118,7 +125,6 @@ public abstract class DpmTestBase extends AndroidTestCase {
                mRealTestContext.getPackageManager().getApplicationInfo(
                        copyFromAdmin.getPackageName(),
                        PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS));

        ai.enabledSetting = enabledSetting == null
                ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED
                : enabledSetting;