• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  */
16 package com.android.server.devicepolicy;
17 
18 import static android.app.AppOpsManager.MODE_ALLOWED;
19 import static android.app.AppOpsManager.MODE_DEFAULT;
20 import static android.app.AppOpsManager.OP_ACTIVATE_VPN;
21 import static android.app.Notification.EXTRA_TITLE;
22 import static android.app.admin.DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE;
23 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
24 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
25 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT;
26 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED;
27 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
28 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
29 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
30 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
31 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
32 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
33 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
34 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD;
35 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
36 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
37 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
38 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO;
39 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
40 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW;
41 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
42 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
43 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR;
44 import static android.app.admin.DevicePolicyManager.WIFI_SECURITY_ENTERPRISE_192;
45 import static android.app.admin.DevicePolicyManager.WIFI_SECURITY_ENTERPRISE_EAP;
46 import static android.app.admin.DevicePolicyManager.WIFI_SECURITY_OPEN;
47 import static android.app.admin.DevicePolicyManager.WIFI_SECURITY_PERSONAL;
48 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
49 import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
50 import static android.location.LocationManager.FUSED_PROVIDER;
51 import static android.location.LocationManager.GPS_PROVIDER;
52 import static android.location.LocationManager.NETWORK_PROVIDER;
53 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT;
54 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE;
55 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK;
56 import static android.net.InetAddresses.parseNumericAddress;
57 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
58 
59 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
60 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
61 import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
62 import static com.android.server.SystemTimeZone.TIME_ZONE_CONFIDENCE_HIGH;
63 import static com.android.server.devicepolicy.DevicePolicyManagerService.ACTION_PROFILE_OFF_DEADLINE;
64 import static com.android.server.devicepolicy.DevicePolicyManagerService.ACTION_TURN_PROFILE_ON_NOTIFICATION;
65 import static com.android.server.devicepolicy.DpmMockContext.CALLER_USER_HANDLE;
66 import static com.android.server.testutils.TestUtils.assertExpectException;
67 
68 import static com.google.common.truth.Truth.assertThat;
69 import static com.google.common.truth.Truth.assertWithMessage;
70 
71 import static org.junit.Assert.fail;
72 import static org.junit.Assume.assumeTrue;
73 import static org.mockito.ArgumentMatchers.any;
74 import static org.mockito.ArgumentMatchers.anyBoolean;
75 import static org.mockito.ArgumentMatchers.anyInt;
76 import static org.mockito.ArgumentMatchers.anyLong;
77 import static org.mockito.ArgumentMatchers.anyString;
78 import static org.mockito.ArgumentMatchers.eq;
79 import static org.mockito.ArgumentMatchers.isNull;
80 import static org.mockito.ArgumentMatchers.longThat;
81 import static org.mockito.Mockito.clearInvocations;
82 import static org.mockito.Mockito.doAnswer;
83 import static org.mockito.Mockito.doReturn;
84 import static org.mockito.Mockito.never;
85 import static org.mockito.Mockito.nullable;
86 import static org.mockito.Mockito.reset;
87 import static org.mockito.Mockito.timeout;
88 import static org.mockito.Mockito.times;
89 import static org.mockito.Mockito.verify;
90 import static org.mockito.Mockito.verifyNoMoreInteractions;
91 import static org.mockito.Mockito.when;
92 import static org.mockito.hamcrest.MockitoHamcrest.argThat;
93 import static org.testng.Assert.assertThrows;
94 
95 import static java.util.Collections.emptyList;
96 
97 import android.Manifest.permission;
98 import android.app.Activity;
99 import android.app.AppOpsManager;
100 import android.app.Notification;
101 import android.app.PendingIntent;
102 import android.app.admin.DeviceAdminReceiver;
103 import android.app.admin.DevicePolicyManager;
104 import android.app.admin.DevicePolicyManagerInternal;
105 import android.app.admin.DevicePolicyManagerLiteInternal;
106 import android.app.admin.FactoryResetProtectionPolicy;
107 import android.app.admin.PasswordMetrics;
108 import android.app.admin.PreferentialNetworkServiceConfig;
109 import android.app.admin.SystemUpdatePolicy;
110 import android.app.admin.WifiSsidPolicy;
111 import android.app.admin.flags.Flags;
112 import android.app.role.RoleManager;
113 import android.content.BroadcastReceiver;
114 import android.content.ComponentName;
115 import android.content.Intent;
116 import android.content.IntentFilter;
117 import android.content.pm.ApplicationInfo;
118 import android.content.pm.PackageInfo;
119 import android.content.pm.PackageManager;
120 import android.content.pm.ResolveInfo;
121 import android.content.pm.StringParceledListSlice;
122 import android.content.pm.UserInfo;
123 import android.graphics.Color;
124 import android.hardware.usb.UsbManager;
125 import android.net.ProfileNetworkPreference;
126 import android.net.Uri;
127 import android.net.wifi.WifiSsid;
128 import android.os.Build;
129 import android.os.Build.VERSION_CODES;
130 import android.os.Bundle;
131 import android.os.IpcDataCache;
132 import android.os.PersistableBundle;
133 import android.os.Process;
134 import android.os.UserHandle;
135 import android.os.UserManager;
136 import android.platform.test.annotations.Presubmit;
137 import android.platform.test.annotations.RequiresFlagsDisabled;
138 import android.platform.test.annotations.RequiresFlagsEnabled;
139 import android.platform.test.flag.junit.CheckFlagsRule;
140 import android.platform.test.flag.junit.DeviceFlagsValueProvider;
141 import android.provider.DeviceConfig;
142 import android.provider.Settings;
143 import android.security.KeyChain;
144 import android.security.keystore.AttestationUtils;
145 import android.telephony.SubscriptionInfo;
146 import android.telephony.TelephonyManager;
147 import android.telephony.data.ApnSetting;
148 import android.test.MoreAsserts;
149 import android.util.ArraySet;
150 import android.util.Log;
151 import android.util.Pair;
152 
153 import androidx.test.filters.FlakyTest;
154 import androidx.test.filters.SmallTest;
155 
156 import com.android.internal.R;
157 import com.android.internal.messages.nano.SystemMessageProto;
158 import com.android.internal.widget.LockPatternUtils;
159 import com.android.internal.widget.LockscreenCredential;
160 import com.android.server.LocalServices;
161 import com.android.server.SystemService;
162 import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
163 import com.android.server.pm.RestrictionsSet;
164 import com.android.server.pm.UserManagerInternal;
165 import com.android.server.pm.UserRestrictionsUtils;
166 
167 import org.hamcrest.BaseMatcher;
168 import org.hamcrest.Description;
169 import org.hamcrest.Matcher;
170 import org.junit.After;
171 import org.junit.Before;
172 import org.junit.Ignore;
173 import org.junit.Rule;
174 import org.junit.Test;
175 import org.mockito.Mockito;
176 import org.mockito.internal.util.collections.Sets;
177 import org.mockito.stubbing.Answer;
178 
179 import java.io.File;
180 import java.net.InetSocketAddress;
181 import java.net.Proxy;
182 import java.nio.charset.StandardCharsets;
183 import java.util.ArrayList;
184 import java.util.Arrays;
185 import java.util.Collections;
186 import java.util.HashMap;
187 import java.util.List;
188 import java.util.Map;
189 import java.util.Set;
190 import java.util.concurrent.TimeUnit;
191 
192 /**
193  * Tests for DevicePolicyManager( and DevicePolicyManagerService).
194  *
195  * <p>Run this test with:
196  *
197  * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.DevicePolicyManagerTest}
198  *
199  */
200 @SmallTest
201 @Presubmit
202 public class DevicePolicyManagerTest extends DpmTestBase {
203 
204     private static final String TAG = DevicePolicyManagerTest.class.getSimpleName();
205 
206     private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
207             permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
208             permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
209     public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
210     public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
211     public static final String NOT_ORG_OWNED_PROFILE_OWNER_MSG =
212             "not the profile owner on organization-owned device";
213     public static final String INVALID_CALLING_IDENTITY_MSG = "Calling identity is not authorized";
214     public static final String ONGOING_CALL_MSG = "ongoing call on the device";
215 
216     @Rule
217     public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
218 
219     // TODO replace all instances of this with explicit {@link #mServiceContext}.
220     @Deprecated
221     private DpmMockContext mContext;
222 
223     private DpmMockContext mServiceContext;
224     private DpmMockContext mAdmin1Context;
225     public DevicePolicyManager dpm;
226     public DevicePolicyManager parentDpm;
227     public DevicePolicyManagerServiceTestable dpms;
228 
229     private boolean mIsAutomotive;
230 
231     /*
232      * The CA cert below is the content of cacert.pem as generated by:
233      *
234      * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
235      */
236     private static final String TEST_CA =
237             "-----BEGIN CERTIFICATE-----\n" +
238             "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
239             "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
240             "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
241             "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
242             "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
243             "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
244             "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
245             "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
246             "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
247             "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
248             "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
249             "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
250             "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
251             "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
252             "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
253             "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
254             "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
255             "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
256             "wQ==\n" +
257             "-----END CERTIFICATE-----\n";
258 
259     // Constants for testing setManagedProfileMaximumTimeOff:
260     // Profile maximum time off value
261     private static final long PROFILE_OFF_TIMEOUT = TimeUnit.DAYS.toMillis(5);
262     // Synthetic time at the beginning of test.
263     private static final long PROFILE_OFF_START = 1;
264     // Time when warning notification should be posted,
265     private static final long PROFILE_OFF_WARNING_TIME =
266             PROFILE_OFF_START + PROFILE_OFF_TIMEOUT - TimeUnit.DAYS.toMillis(1);
267     // Time when the apps should be suspended
268     private static final long PROFILE_OFF_DEADLINE = PROFILE_OFF_START + PROFILE_OFF_TIMEOUT;
269     // Notification title and text for setManagedProfileMaximumTimeOff tests:
270     private static final String PROFILE_OFF_SUSPENSION_TITLE = "suspension_title";
271     private static final String PROFILE_OFF_SUSPENSION_TEXT = "suspension_text";
272     private static final String PROFILE_OFF_SUSPENSION_SOON_TEXT = "suspension_tomorrow_text";
273     private static final String FLAG_ENABLE_WORK_PROFILE_TELEPHONY =
274             "enable_work_profile_telephony";
275 
276     @Before
setUp()277     public void setUp() throws Exception {
278 
279         // Disable caches in this test process. This must happen early, since some of the
280         // following initialization steps invalidate caches.
281         IpcDataCache.disableForTestMode();
282 
283         mContext = getContext();
284         mServiceContext = mContext;
285         mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
286         when(getServices().userManagerInternal.getUserIds()).thenReturn(new int[]{0});
287         when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
288                 .thenReturn(true);
289         doReturn(Collections.singletonList(new ResolveInfo()))
290                 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
291                         any(Intent.class),
292                         anyInt(),
293                         any(UserHandle.class));
294 
295         // Make createContextAsUser to work.
296         mContext.packageName = "com.android.frameworks.servicestests";
297         getServices().addPackageContext(UserHandle.of(0), mContext);
298         getServices().addPackageContext(UserHandle.of(CALLER_USER_HANDLE), mContext);
299 
300         // By default, pretend all users are running and unlocked.
301         when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
302 
303         initializeDpms();
304 
305         Mockito.reset(getServices().usageStatsManagerInternal);
306         Mockito.reset(getServices().networkPolicyManagerInternal);
307         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
308         setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
309         setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
310         setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
311 
312         mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
313         mAdmin1Context.packageName = admin1.getPackageName();
314         mAdmin1Context.applicationInfo = new ApplicationInfo();
315         mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
316 
317         setUpUserManager();
318 
319         when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
320 
321         mIsAutomotive = mContext.getPackageManager()
322                 .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
323 
324         final String TEST_STRING = "{count, plural,\n"
325                 + "        =1    {Test for exactly 1 cert out of 4}\n"
326                 + "        other {Test for exactly # certs out of 4}\n"
327                 + "}";
328         doReturn(TEST_STRING)
329                 .when(mContext.resources)
330                 .getString(R.string.ssl_ca_cert_warning);
331     }
332 
getMockTransferMetadataManager()333     private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
334         return dpms.mTransferOwnershipMetadataManager;
335     }
336 
337     @After
tearDown()338     public void tearDown() throws Exception {
339         flushTasks(dpms);
340         getMockTransferMetadataManager().deleteMetadataFile();
341     }
342 
initializeDpms()343     private void initializeDpms() {
344         // Need clearCallingIdentity() to pass permission checks.
345         final long ident = mContext.binder.clearCallingIdentity();
346 
347         dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
348         dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
349         dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
350 
351         dpm = new DevicePolicyManagerTestable(mContext, dpms);
352 
353         parentDpm = new DevicePolicyManagerTestable(mServiceContext, dpms,
354                 /* parentInstance= */true);
355 
356         mContext.binder.restoreCallingIdentity(ident);
357     }
358 
setUpUserManager()359     private void setUpUserManager() {
360         // Emulate UserManager.set/getApplicationRestriction().
361         final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
362 
363         // UM.setApplicationRestrictions() will save to appRestrictions.
364         doAnswer((Answer<Void>) invocation -> {
365             String pkg = (String) invocation.getArguments()[0];
366             Bundle bundle = (Bundle) invocation.getArguments()[1];
367             UserHandle user = (UserHandle) invocation.getArguments()[2];
368 
369             appRestrictions.put(Pair.create(pkg, user), bundle);
370 
371             return null;
372         }).when(getServices().userManager).setApplicationRestrictions(
373                 anyString(), nullable(Bundle.class), any(UserHandle.class));
374 
375         // UM.getApplicationRestrictions() will read from appRestrictions.
376         doAnswer((Answer<Bundle>) invocation -> {
377             String pkg = (String) invocation.getArguments()[0];
378             UserHandle user = (UserHandle) invocation.getArguments()[1];
379 
380             return appRestrictions.get(Pair.create(pkg, user));
381         }).when(getServices().userManager).getApplicationRestrictions(
382                 anyString(), any(UserHandle.class));
383 
384         // Emulate UserManager.setUserRestriction/getUserRestrictions
385         final Map<UserHandle, Bundle> userRestrictions = new HashMap<>();
386 
387         doAnswer((Answer<Void>) invocation -> {
388             String key = (String) invocation.getArguments()[0];
389             boolean value = (Boolean) invocation.getArguments()[1];
390             UserHandle user = (UserHandle) invocation.getArguments()[2];
391             Bundle userBundle = userRestrictions.getOrDefault(user, new Bundle());
392             userBundle.putBoolean(key, value);
393 
394             userRestrictions.put(user, userBundle);
395             return null;
396         }).when(getServices().userManager).setUserRestriction(
397                 anyString(), anyBoolean(), any(UserHandle.class));
398 
399         doAnswer((Answer<Boolean>) invocation -> {
400             String key = (String) invocation.getArguments()[0];
401             UserHandle user = (UserHandle) invocation.getArguments()[1];
402             Bundle userBundle = userRestrictions.getOrDefault(user, new Bundle());
403             return userBundle.getBoolean(key);
404         }).when(getServices().userManager).hasUserRestriction(
405                 anyString(), any(UserHandle.class));
406 
407         // Add the first secondary user.
408         getServices().addUser(CALLER_USER_HANDLE, 0, UserManager.USER_TYPE_FULL_SECONDARY);
409     }
410 
setAsProfileOwner(ComponentName admin)411     private void setAsProfileOwner(ComponentName admin) {
412         final long ident = mServiceContext.binder.clearCallingIdentity();
413 
414         mServiceContext.binder.callingUid =
415                 UserHandle.getUid(CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
416         runAsCaller(mServiceContext, dpms, dpm -> {
417             // PO needs to be a DA.
418             dpm.setActiveAdmin(admin, /*replace=*/ false);
419             // Fire!
420             assertThat(dpm.setProfileOwner(admin, CALLER_USER_HANDLE)).isTrue();
421             // Check
422             assertThat(dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE)).isEqualTo(admin);
423         });
424 
425         mServiceContext.binder.restoreCallingIdentity(ident);
426     }
427 
428     @Test
testHasNoFeature()429     public void testHasNoFeature() throws Exception {
430         when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
431                 .thenReturn(false);
432 
433         new DevicePolicyManagerServiceTestable(getServices(), mContext);
434 
435         // If the device has no DPMS feature, it shouldn't register the local service.
436         assertThat(LocalServices.getService(DevicePolicyManagerInternal.class)).isNull();
437 
438         // But should still register the lite one
439         assertThat(LocalServices.getService(DevicePolicyManagerLiteInternal.class)).isNotNull();
440     }
441 
442     @Test
testLoadAdminData()443     public void testLoadAdminData() throws Exception {
444         // Device owner in SYSTEM_USER
445         setDeviceOwner();
446         // Profile owner in CALLER_USER_HANDLE
447         setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
448         setAsProfileOwner(admin2);
449         // Active admin in CALLER_USER_HANDLE
450         final int ANOTHER_UID = UserHandle.getUid(CALLER_USER_HANDLE, 1306);
451         setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
452         dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false, CALLER_USER_HANDLE);
453         assertThat(dpm.isAdminActiveAsUser(adminAnotherPackage, CALLER_USER_HANDLE)).isTrue();
454 
455         initializeDpms();
456 
457         // Verify
458         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
459                 MockUtils.checkApps(admin1.getPackageName()),
460                 eq(UserHandle.USER_SYSTEM));
461         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
462                 MockUtils.checkApps(admin2.getPackageName(),
463                         adminAnotherPackage.getPackageName()),
464                 eq(CALLER_USER_HANDLE));
465         verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
466         verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
467     }
468 
469     @Test
testLoadAdminData_noAdmins()470     public void testLoadAdminData_noAdmins() throws Exception {
471         final int ANOTHER_USER_ID = 15;
472         getServices().addUser(ANOTHER_USER_ID, 0, "");
473 
474         initializeDpms();
475 
476         // Verify
477         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
478                 null, CALLER_USER_HANDLE);
479         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
480                 null, ANOTHER_USER_ID);
481         verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
482         verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
483     }
484 
485     /**
486      * Caller doesn't have proper permissions.
487      */
488     @Test
testSetActiveAdmin_SecurityException()489     public void testSetActiveAdmin_SecurityException() {
490         // 1. Failure cases.
491 
492         // Caller doesn't have MANAGE_DEVICE_ADMINS.
493         assertExpectException(SecurityException.class, /* messageRegex= */ null,
494                 () -> dpm.setActiveAdmin(admin1, false));
495 
496         // Caller has MANAGE_DEVICE_ADMINS, but for different user.
497         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
498 
499         assertExpectException(SecurityException.class, /* messageRegex= */ null,
500                 () -> dpm.setActiveAdmin(admin1, false, CALLER_USER_HANDLE + 1));
501     }
502 
503     /**
504      * Test for:
505      * {@link DevicePolicyManager#setActiveAdmin}
506      * with replace=false and replace=true
507      * {@link DevicePolicyManager#isAdminActive}
508      * {@link DevicePolicyManager#isAdminActiveAsUser}
509      * {@link DevicePolicyManager#getActiveAdmins}
510      * {@link DevicePolicyManager#getActiveAdminsAsUser}
511      */
512     @Test
testSetActiveAdmin()513     public void testSetActiveAdmin() throws Exception {
514         // 1. Make sure the caller has proper permissions.
515         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
516 
517         // 2. Call the API.
518         dpm.setActiveAdmin(admin1, /* replace =*/ false);
519 
520         // 3. Verify internal calls.
521 
522         // Check if the boradcast is sent.
523         verify(mContext.spiedContext).sendBroadcastAsUser(
524                 MockUtils.checkIntentAction(
525                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
526                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
527                 eq(null),
528                 any(Bundle.class));
529         verify(mContext.spiedContext).sendBroadcastAsUser(
530                 MockUtils.checkIntentAction(
531                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
532                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
533                 eq(null),
534                 any(Bundle.class));
535 
536         verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
537                 eq(admin1.getPackageName()),
538                 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
539                 eq(PackageManager.DONT_KILL_APP),
540                 eq(CALLER_USER_HANDLE),
541                 anyString());
542 
543         verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
544                 admin1.getPackageName(), CALLER_USER_HANDLE);
545 
546         // TODO Verify other calls too.
547 
548         // Make sure it's active admin1.
549         assertThat(dpm.isAdminActive(admin1)).isTrue();
550         assertThat(dpm.isAdminActive(admin2)).isFalse();
551         assertThat(dpm.isAdminActive(admin3)).isFalse();
552 
553         // But not admin1 for a different user.
554 
555         // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
556         // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
557         mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
558 
559         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE + 1)).isFalse();
560         assertThat(dpm.isAdminActiveAsUser(admin2, CALLER_USER_HANDLE + 1)).isFalse();
561 
562         mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
563 
564         // Next, add one more admin.
565         // Before doing so, update the application info, now it's enabled.
566         setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
567                 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
568 
569         dpm.setActiveAdmin(admin2, /* replace =*/ false);
570 
571         // Now we have two admins.
572         assertThat(dpm.isAdminActive(admin1)).isTrue();
573         assertThat(dpm.isAdminActive(admin2)).isTrue();
574         assertThat(dpm.isAdminActive(admin3)).isFalse();
575 
576         // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
577         // again.  (times(1) because it was previously called for admin1)
578         verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
579                 eq(admin1.getPackageName()),
580                 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
581                 eq(PackageManager.DONT_KILL_APP),
582                 eq(CALLER_USER_HANDLE),
583                 anyString());
584 
585         // times(2) because it was previously called for admin1 which is in the same package
586         // as admin2.
587         verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
588                 admin2.getPackageName(), CALLER_USER_HANDLE);
589 
590         // 4. Add the same admin1 again without replace, which should throw.
591         assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
592                 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
593 
594         // 5. Add the same admin1 again with replace, which should succeed.
595         dpm.setActiveAdmin(admin1, /* replace =*/ true);
596 
597         // TODO make sure it's replaced.
598 
599         // 6. Test getActiveAdmins()
600         List<ComponentName> admins = dpm.getActiveAdmins();
601         assertThat(admins.size()).isEqualTo(2);
602         assertThat(admins.get(0)).isEqualTo(admin1);
603         assertThat(admins.get(1)).isEqualTo(admin2);
604 
605         // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
606         // replaced
607         verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
608 
609         // Another user has no admins.
610         mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
611 
612         assertThat(DpmTestUtils.getListSizeAllowingNull(
613         dpm.getActiveAdminsAsUser(CALLER_USER_HANDLE + 1))).isEqualTo(0);
614 
615         mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
616     }
617 
618     @Test
testSetActiveAdmin_multiUsers()619     public void testSetActiveAdmin_multiUsers() throws Exception {
620 
621         final int ANOTHER_USER_ID = 100;
622         final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
623 
624         getServices().addUser(ANOTHER_USER_ID, 0, ""); // Add one more user.
625 
626         // Set up pacakge manager for the other user.
627         setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
628 
629         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
630 
631         dpm.setActiveAdmin(admin1, /* replace =*/ false);
632 
633         mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
634         dpm.setActiveAdmin(admin2, /* replace =*/ false);
635 
636 
637         mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
638         assertThat(dpm.isAdminActive(admin1)).isTrue();
639         assertThat(dpm.isAdminActive(admin2)).isFalse();
640 
641         mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
642         assertThat(dpm.isAdminActive(admin1)).isFalse();
643         assertThat(dpm.isAdminActive(admin2)).isTrue();
644     }
645 
646     /**
647      * Test for:
648      * {@link DevicePolicyManager#setActiveAdmin}
649      * with replace=false
650      */
651     @Test
testSetActiveAdmin_twiceWithoutReplace()652     public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
653         // 1. Make sure the caller has proper permissions.
654         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
655 
656         dpm.setActiveAdmin(admin1, /* replace =*/ false);
657         assertThat(dpm.isAdminActive(admin1)).isTrue();
658 
659         // Add the same admin1 again without replace, which should throw.
660         assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
661                 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
662     }
663 
664     /**
665      * Test for:
666      * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
667      * BIND_DEVICE_ADMIN.
668      */
669     @Test
testSetActiveAdmin_permissionCheck()670     public void testSetActiveAdmin_permissionCheck() throws Exception {
671         // 1. Make sure the caller has proper permissions.
672         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
673 
674         assertExpectException(IllegalArgumentException.class,
675                 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
676                 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
677         assertThat(dpm.isAdminActive(adminNoPerm)).isFalse();
678 
679         // Change the target API level to MNC.  Now it can be set as DA.
680         setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
681                 VERSION_CODES.M);
682         dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
683         assertThat(dpm.isAdminActive(adminNoPerm)).isTrue();
684 
685         // TODO Test the "load from the file" case where DA will still be loaded even without
686         // BIND_DEVICE_ADMIN and target API is N.
687     }
688 
689     /**
690      * Test for:
691      * {@link DevicePolicyManager#removeActiveAdmin}
692      */
693     @Test
testRemoveActiveAdmin_SecurityException()694     public void testRemoveActiveAdmin_SecurityException() {
695         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
696 
697         // Add admin.
698 
699         dpm.setActiveAdmin(admin1, /* replace =*/ false);
700 
701         assertThat(dpm.isAdminActive(admin1)).isTrue();
702 
703         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
704 
705         // Directly call the DPMS method with a different userid, which should fail.
706         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
707                 () -> dpms.removeActiveAdmin(admin1, CALLER_USER_HANDLE + 1));
708 
709         // Try to remove active admin with a different caller userid should fail too, without
710         // having MANAGE_DEVICE_ADMINS.
711         mContext.callerPermissions.clear();
712 
713         // Change the caller, and call into DPMS directly with a different user-id.
714 
715         mContext.binder.callingUid = 1234567;
716         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
717                 () -> dpms.removeActiveAdmin(admin1, CALLER_USER_HANDLE));
718     }
719 
720     /**
721      * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
722      * (because we can't send the remove broadcast).
723      */
724     @Test
testRemoveActiveAdmin_userNotRunningOrLocked()725     public void testRemoveActiveAdmin_userNotRunningOrLocked() {
726         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
727 
728         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
729 
730         // Add admin.
731 
732         dpm.setActiveAdmin(admin1, /* replace =*/ false);
733 
734         assertThat(dpm.isAdminActive(admin1)).isTrue();
735 
736         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
737 
738         // 1. User not unlocked.
739         setUserUnlocked(CALLER_USER_HANDLE, false);
740         assertExpectException(IllegalStateException.class,
741                 /* messageRegex= */ "User must be running and unlocked",
742                 () -> dpm.removeActiveAdmin(admin1));
743 
744         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
745         verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
746                 null, CALLER_USER_HANDLE);
747 
748         // 2. User unlocked.
749         setUserUnlocked(CALLER_USER_HANDLE, true);
750 
751         dpm.removeActiveAdmin(admin1);
752         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
753         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
754                 null, CALLER_USER_HANDLE);
755     }
756 
757     /**
758      * Test for:
759      * {@link DevicePolicyManager#removeActiveAdmin}
760      */
761     @Test
testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL()762     public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
763         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
764         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
765 
766         // Add admin1.
767 
768         dpm.setActiveAdmin(admin1, /* replace =*/ false);
769 
770         assertThat(dpm.isAdminActive(admin1)).isTrue();
771         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
772 
773         // Different user, but should work, because caller has proper permissions.
774         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
775 
776         // Change the caller, and call into DPMS directly with a different user-id.
777         mContext.binder.callingUid = 1234567;
778 
779         dpms.removeActiveAdmin(admin1, CALLER_USER_HANDLE);
780         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
781         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
782                 null, CALLER_USER_HANDLE);
783 
784         // TODO DO Still can't be removed in this case.
785     }
786 
787     /**
788      * Test for:
789      * {@link DevicePolicyManager#removeActiveAdmin}
790      */
791     @Test
testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS()792     public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
793         // Need MANAGE_DEVICE_ADMINS for setActiveAdmin.  We'll remove it later.
794         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
795 
796         // Add admin1.
797 
798         dpm.setActiveAdmin(admin1, /* replace =*/ false);
799 
800         assertThat(dpm.isAdminActive(admin1)).isTrue();
801         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
802 
803         // Broadcast from saveSettingsLocked().
804         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
805                 MockUtils.checkIntentAction(
806                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
807                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
808                 eq(null),
809                 any(Bundle.class));
810 
811         // Remove.  No permissions, but same user, so it'll work.
812         mContext.callerPermissions.clear();
813         dpm.removeActiveAdmin(admin1);
814 
815         verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
816                 MockUtils.checkIntentAction(
817                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
818                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
819                 isNull(),
820                 eq(AppOpsManager.OP_NONE),
821                 any(Bundle.class),
822                 any(BroadcastReceiver.class),
823                 eq(dpms.mHandler),
824                 eq(Activity.RESULT_OK),
825                 isNull(),
826                 isNull());
827 
828         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
829         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
830                 null, CALLER_USER_HANDLE);
831 
832         // Again broadcast from saveSettingsLocked().
833         verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
834                 MockUtils.checkIntentAction(
835                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
836                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
837                 eq(null),
838                 any(Bundle.class));
839 
840         // TODO Check other internal calls.
841     }
842 
843     @Test
testRemoveActiveAdmin_multipleAdminsInUser()844     public void testRemoveActiveAdmin_multipleAdminsInUser() {
845         // Need MANAGE_DEVICE_ADMINS for setActiveAdmin.  We'll remove it later.
846         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
847 
848         // Add admin1.
849         dpm.setActiveAdmin(admin1, /* replace =*/ false);
850 
851         assertThat(dpm.isAdminActive(admin1)).isTrue();
852         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
853 
854         // Add admin2.
855         dpm.setActiveAdmin(admin2, /* replace =*/ false);
856 
857         assertThat(dpm.isAdminActive(admin2)).isTrue();
858         assertThat(dpm.isRemovingAdmin(admin2, CALLER_USER_HANDLE)).isFalse();
859 
860         // Broadcast from saveSettingsLocked().
861         verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
862                 MockUtils.checkIntentAction(
863                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
864                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
865                 eq(null),
866                 any(Bundle.class));
867 
868         // Remove.  No permissions, but same user, so it'll work.
869         mContext.callerPermissions.clear();
870         dpm.removeActiveAdmin(admin1);
871 
872         verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
873                 MockUtils.checkIntentAction(
874                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
875                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
876                 isNull(),
877                 eq(AppOpsManager.OP_NONE),
878                 any(Bundle.class),
879                 any(BroadcastReceiver.class),
880                 eq(dpms.mHandler),
881                 eq(Activity.RESULT_OK),
882                 isNull(),
883                 isNull());
884 
885         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
886         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
887                 MockUtils.checkApps(admin2.getPackageName()),
888                 eq(CALLER_USER_HANDLE));
889 
890         // Again broadcast from saveSettingsLocked().
891         verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
892                 MockUtils.checkIntentAction(
893                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
894                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
895                 eq(null),
896                 any(Bundle.class));
897     }
898 
899     /**
900      * Test for:
901      * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
902      */
903     @Test
testForceRemoveActiveAdmin_nonShellCaller()904     public void testForceRemoveActiveAdmin_nonShellCaller() throws Exception {
905         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
906 
907         // Add admin.
908         setupPackageInPackageManager(admin1.getPackageName(),
909                 /* userId= */ CALLER_USER_HANDLE,
910                 /* appId= */ 10138,
911                 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
912         dpm.setActiveAdmin(admin1, /* replace =*/ false);
913         assertThat(dpm.isAdminActive(admin1)).isTrue();
914 
915         // Calling from a non-shell uid should fail with a SecurityException
916         mContext.binder.callingUid = 123456;
917         assertExpectException(SecurityException.class,
918                 /* messageRegex = */ null,
919                 () -> dpms.forceRemoveActiveAdmin(admin1, CALLER_USER_HANDLE));
920     }
921 
922     /**
923      * Test for:
924      * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
925      */
926     @Test
testForceRemoveActiveAdmin_nonShellCallerWithPermission()927     public void testForceRemoveActiveAdmin_nonShellCallerWithPermission() throws Exception {
928         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
929 
930         // Add admin.
931         setupPackageInPackageManager(admin1.getPackageName(),
932                 /* userId= */ CALLER_USER_HANDLE,
933                 /* appId= */ 10138,
934                 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
935         dpm.setActiveAdmin(admin1, /* replace =*/ false);
936         assertThat(dpm.isAdminActive(admin1)).isTrue();
937 
938         mContext.binder.callingUid = 123456;
939         mContext.callerPermissions.add(
940                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
941         dpms.forceRemoveActiveAdmin(admin1, CALLER_USER_HANDLE);
942 
943         mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
944         // Verify
945         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
946         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
947                 null, CALLER_USER_HANDLE);
948     }
949 
950     /**
951      * Test for:
952      * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
953      */
954     @Test
testForceRemoveActiveAdmin_ShellCaller()955     public void testForceRemoveActiveAdmin_ShellCaller() throws Exception {
956         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
957 
958         // Add admin.
959         setupPackageInPackageManager(admin1.getPackageName(),
960                 /* userId= */ CALLER_USER_HANDLE,
961                 /* appId= */ 10138,
962                 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
963         dpm.setActiveAdmin(admin1, /* replace =*/ false);
964         assertThat(dpm.isAdminActive(admin1)).isTrue();
965 
966         mContext.binder.callingUid = Process.SHELL_UID;
967         dpms.forceRemoveActiveAdmin(admin1, CALLER_USER_HANDLE);
968 
969         mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
970         // Verify
971         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
972         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
973                 null, CALLER_USER_HANDLE);
974     }
975 
976     /**
977      * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
978      *
979      * Validates that when the password history length is set, it is persisted after rebooting
980      */
981     @Test
testSaveAndLoadPasswordHistoryLength_persistedAfterReboot()982     public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
983         int passwordHistoryLength = 2;
984 
985         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
986         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
987         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
988 
989         // Install admin1 on system user.
990         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
991 
992         // Set admin1 to active admin and device owner
993         dpm.setActiveAdmin(admin1, false);
994         dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM);
995 
996         // Save password history length
997         dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
998 
999         assertThat(passwordHistoryLength).isEqualTo(dpm.getPasswordHistoryLength(admin1));
1000 
1001         initializeDpms();
1002         reset(mContext.spiedContext);
1003 
1004         // Password history length should persist after rebooted
1005         assertThat(passwordHistoryLength).isEqualTo(dpm.getPasswordHistoryLength(admin1));
1006     }
1007 
1008     /**
1009      * Test for: {@link DevicePolicyManager#reportPasswordChanged}
1010      *
1011      * Validates that when the password for a user changes, the notification broadcast intent
1012      * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
1013      * addition to ones in the original user.
1014      */
1015     @Test
testSetActivePasswordState_sendToProfiles()1016     public void testSetActivePasswordState_sendToProfiles() throws Exception {
1017         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
1018 
1019         final int MANAGED_PROFILE_USER_ID = 78;
1020         final int MANAGED_PROFILE_ADMIN_UID =
1021                 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
1022 
1023         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1024         mContext.packageName = admin1.getPackageName();
1025 
1026         // Add a managed profile belonging to the system user.
1027         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
1028 
1029         // Change the parent user's password.
1030         dpm.reportPasswordChanged(new PasswordMetrics(CREDENTIAL_TYPE_PASSWORD),
1031                 UserHandle.USER_SYSTEM);
1032 
1033         // The managed profile owner should receive this broadcast.
1034         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
1035         intent.setComponent(admin1);
1036         intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
1037 
1038         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
1039                 MockUtils.checkIntent(intent),
1040                 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
1041                 eq(null),
1042                 any(Bundle.class));
1043     }
1044 
1045     /**
1046      * Test for: @{link DevicePolicyManager#reportPasswordChanged}
1047      *
1048      * Validates that when the password for a managed profile changes, the notification broadcast
1049      * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
1050      * its parent.
1051      */
1052     @Test
testSetActivePasswordState_notSentToParent()1053     public void testSetActivePasswordState_notSentToParent() throws Exception {
1054         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
1055 
1056         final int MANAGED_PROFILE_USER_ID = 78;
1057         final int MANAGED_PROFILE_ADMIN_UID =
1058                 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
1059 
1060         // Configure system as having separate profile challenge.
1061         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1062         mContext.packageName = admin1.getPackageName();
1063         doReturn(true).when(getServices().lockPatternUtils)
1064                 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
1065 
1066         // Add a managed profile belonging to the system user.
1067         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
1068 
1069         // Change the profile's password.
1070         dpm.reportPasswordChanged(new PasswordMetrics(CREDENTIAL_TYPE_PASSWORD),
1071                 MANAGED_PROFILE_USER_ID);
1072 
1073         // Both the device owner and the managed profile owner should receive this broadcast.
1074         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
1075         intent.setComponent(admin1);
1076         intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
1077 
1078         verify(mContext.spiedContext, never()).sendBroadcastAsUser(
1079                 MockUtils.checkIntent(intent),
1080                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
1081                 eq(null),
1082                 any(Bundle.class));
1083         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
1084                 MockUtils.checkIntent(intent),
1085                 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
1086                 eq(null),
1087                 any(Bundle.class));
1088     }
1089 
1090     /**
1091      * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
1092      */
1093     @Test
testSetDeviceOwner()1094     public void testSetDeviceOwner() throws Exception {
1095         setDeviceOwner();
1096 
1097         // Try to set a profile owner on the same user, which should fail.
1098         setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1099         dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
1100         assertExpectException(IllegalStateException.class,
1101                 /* messageRegex= */ "already has a device owner",
1102                 () -> dpm.setProfileOwner(admin2, UserHandle.USER_SYSTEM));
1103 
1104         // DO admin can't be deactivated.
1105         dpm.removeActiveAdmin(admin1);
1106         assertThat(dpm.isAdminActive(admin1)).isTrue();
1107 
1108         // TODO Test getDeviceOwnerName() too. To do so, we need to change
1109         // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
1110     }
1111 
setDeviceOwner()1112     private void setDeviceOwner() throws Exception {
1113         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1114         mContext.callerPermissions.add(permission.MANAGE_USERS);
1115         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1116         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1117 
1118         // In this test, change the caller user to "system".
1119         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1120 
1121         // Make sure admin1 is installed on system user.
1122         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1123 
1124         // Check various get APIs.
1125         checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
1126 
1127         // DO needs to be an DA.
1128         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1129 
1130         // Fire!
1131         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
1132 
1133         // getDeviceOwnerComponent should return the admin1 component.
1134         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
1135         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1136 
1137         // Check various get APIs.
1138         checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
1139 
1140         // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
1141         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1142         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1143         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1144 
1145         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1146 
1147         // Verify internal calls.
1148         verify(getServices().userManager, times(1)).setUserRestriction(
1149                 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
1150                 eq(true), eq(UserHandle.SYSTEM));
1151 
1152         verify(getServices().userManager, times(1)).setUserRestriction(
1153                 eq(UserManager.DISALLOW_ADD_CLONE_PROFILE),
1154                 eq(true), eq(UserHandle.SYSTEM));
1155 
1156         verify(getServices().userManager, times(1)).setUserRestriction(
1157                 eq(UserManager.DISALLOW_ADD_PRIVATE_PROFILE),
1158                 eq(true), eq(UserHandle.SYSTEM));
1159 
1160         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
1161                 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1162                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1163 
1164         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1165     }
1166 
1167     // TODO(b/174859111): move to automotive-only section
setDeviceOwner_headlessSystemUser()1168     private void setDeviceOwner_headlessSystemUser() throws Exception {
1169         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1170         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1171         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1172         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
1173         mContext.callerPermissions.add(permission.MANAGE_USERS);
1174 
1175         when(getServices().iactivityManager.getCurrentUser()).thenReturn(
1176                 new UserInfo(DpmMockContext.CALLER_USER_HANDLE, "caller",  /* flags=*/ 0));
1177         // Check various get APIs.
1178         checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
1179 
1180         final long ident = mServiceContext.binder.clearCallingIdentity();
1181 
1182         mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
1183 
1184         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1185         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1186 
1187         // Set device owner
1188         runAsCaller(mServiceContext, dpms, dpm -> {
1189             // DO needs to be a DA
1190             dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1191             // DO should be set on headless system user
1192             assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
1193             // PO should be set on calling user.
1194             assertThat(dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE)).isEqualTo(admin1);
1195         });
1196 
1197         mServiceContext.binder.restoreCallingIdentity(ident);
1198 
1199         // Check various get APIs.
1200         checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
1201 
1202         // Add MANAGE_USERS or test purpose.
1203         mContext.callerPermissions.add(permission.MANAGE_USERS);
1204         // getDeviceOwnerComponent should *NOT* return the admin1 component for calling user.
1205         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isNull();
1206         // Device owner should be set on system user.
1207         assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM);
1208 
1209         // Set calling user to be system user.
1210         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1211 
1212         // Device owner component should be admin1
1213         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
1214         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1215 
1216         // Verify internal calls.
1217         verify(mContext.spiedContext).sendBroadcastAsUser(
1218                 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1219                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1220     }
1221 
checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner)1222     private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
1223         final int origCallingUser = mContext.binder.callingUid;
1224         final List origPermissions = new ArrayList(mContext.callerPermissions);
1225         mContext.callerPermissions.clear();
1226 
1227         mContext.callerPermissions.add(permission.MANAGE_USERS);
1228 
1229         mContext.binder.callingUid = Process.SYSTEM_UID;
1230 
1231         // TODO Test getDeviceOwnerName() too.  To do so, we need to change
1232         // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
1233         if (hasDeviceOwner) {
1234             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue();
1235             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue();
1236             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
1237 
1238             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue();
1239             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1240             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM);
1241         } else {
1242             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse();
1243             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse();
1244             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1245 
1246             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse();
1247             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null);
1248             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL);
1249         }
1250 
1251         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1252         if (hasDeviceOwner) {
1253             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue();
1254             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue();
1255             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
1256 
1257             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue();
1258             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1259             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM);
1260         } else {
1261             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse();
1262             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse();
1263             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1264 
1265             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse();
1266             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null);
1267             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL);
1268         }
1269 
1270         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1271         // Still with MANAGE_USERS.
1272         assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse();
1273         assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse();
1274         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1275 
1276         if (hasDeviceOwner) {
1277             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue();
1278             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1279             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM);
1280         } else {
1281             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse();
1282             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null);
1283             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL);
1284         }
1285 
1286         mContext.binder.callingUid = Process.SYSTEM_UID;
1287         mContext.callerPermissions.remove(permission.MANAGE_USERS);
1288         // System can still call "OnAnyUser" without MANAGE_USERS.
1289         if (hasDeviceOwner) {
1290             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue();
1291             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue();
1292             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
1293 
1294             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue();
1295             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1296             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM);
1297         } else {
1298             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse();
1299             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse();
1300             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1301 
1302             assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse();
1303             assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null);
1304             assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL);
1305         }
1306 
1307         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1308         // Still no MANAGE_USERS.
1309         if (hasDeviceOwner) {
1310             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue();
1311             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue();
1312             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
1313         } else {
1314             assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse();
1315             assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse();
1316             assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1317         }
1318 
1319         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1320                 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1321         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1322                 dpm::getDeviceOwnerComponentOnAnyUser);
1323         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1324                 dpm::getDeviceOwnerUserId);
1325         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1326                 dpm::getDeviceOwnerNameOnAnyUser);
1327 
1328         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1329         // Still no MANAGE_USERS.
1330         assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse();
1331         assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse();
1332         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null);
1333 
1334         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1335                 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1336         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1337                 dpm::getDeviceOwnerComponentOnAnyUser);
1338         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1339                 dpm::getDeviceOwnerUserId);
1340         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1341                 dpm::getDeviceOwnerNameOnAnyUser);
1342 
1343         // Restore.
1344         mContext.binder.callingUid = origCallingUser;
1345         mContext.callerPermissions.addAll(origPermissions);
1346     }
1347 
1348 
1349     /**
1350      * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1351      */
1352     @Test
testSetDeviceOwner_noSuchPackage()1353     public void testSetDeviceOwner_noSuchPackage() {
1354         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1355         mContext.callerPermissions.add(permission.MANAGE_USERS);
1356         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1357         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1358 
1359         // Call from a process on the system user.
1360         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1361 
1362         assertExpectException(IllegalArgumentException.class,
1363                 /* messageRegex= */ "Invalid component",
1364                 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"),
1365                         UserHandle.USER_SYSTEM));
1366     }
1367 
1368     @Test
testSetDeviceOwner_failures()1369     public void testSetDeviceOwner_failures() throws Exception {
1370         // TODO Test more failure cases.  Basically test all chacks in enforceCanSetDeviceOwner().
1371         // Package doesn't exist and caller is not system
1372         assertExpectException(SecurityException.class,
1373                 /* messageRegex= */ "Calling identity is not authorized",
1374                 () -> dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM));
1375 
1376         // Package exists, but caller is not system
1377         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1378         assertExpectException(SecurityException.class,
1379                 /* messageRegex= */ "Calling identity is not authorized",
1380                 () -> dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM));
1381     }
1382 
1383     @Test
1384     @Ignore("b/277916462")
testClearDeviceOwner()1385     public void testClearDeviceOwner() throws Exception {
1386         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1387         mContext.callerPermissions.add(permission.MANAGE_USERS);
1388         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1389         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1390 
1391         // Set admin1 as a DA to the secondary user.
1392         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1393 
1394         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1395 
1396         // Set admin 1 as the DO to the system user.
1397 
1398         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1399         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1400         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1401         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
1402         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1403 
1404         dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1405         when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
1406                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
1407 
1408         assertThat(dpm.isAdminActive(admin1)).isTrue();
1409         assertThat(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)).isFalse();
1410 
1411         // Set up other mocks.
1412         when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
1413 
1414         // Now call clear.
1415         getServices().addTestPackageUid(admin1.getPackageName(),
1416                 DpmMockContext.CALLER_SYSTEM_USER_UID);
1417 
1418         // But first pretend the user is locked.  Then it should fail.
1419         when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
1420         assertExpectException(IllegalStateException.class,
1421                 /* messageRegex= */ "User must be running and unlocked",
1422                 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
1423 
1424         when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1425         dpm.clearDeviceOwnerApp(admin1.getPackageName());
1426 
1427         // Now DO shouldn't be set.
1428         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isNull();
1429 
1430         verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
1431                 eq(false),
1432                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1433 
1434         verify(getServices().userManager)
1435                 .setUserRestriction(eq(UserManager.DISALLOW_ADD_CLONE_PROFILE), eq(false),
1436                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1437 
1438         verify(getServices().userManager)
1439                 .setUserRestriction(eq(UserManager.DISALLOW_ADD_PRIVATE_PROFILE), eq(false),
1440                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1441 
1442         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1443                 eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(),
1444                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
1445 
1446         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1447                 null, UserHandle.USER_SYSTEM);
1448 
1449         assertThat(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)).isFalse();
1450 
1451         // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1452         // and once for clearing it.
1453         verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1454                 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1455                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1456         // TODO Check other calls.
1457     }
1458 
1459     @Test
testDeviceOwnerBackupActivateDeactivate()1460     public void testDeviceOwnerBackupActivateDeactivate() throws Exception {
1461         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1462         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1463 
1464         // Set admin1 as a DA to the secondary user.
1465         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1466         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1467         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1468         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
1469 
1470         verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1471                 eq(UserHandle.USER_SYSTEM), eq(false));
1472 
1473         dpm.clearDeviceOwnerApp(admin1.getPackageName());
1474 
1475         verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1476                 eq(UserHandle.USER_SYSTEM), eq(true));
1477     }
1478 
1479     @Test
testProfileOwnerBackupActivateDeactivate()1480     public void testProfileOwnerBackupActivateDeactivate() throws Exception {
1481         setAsProfileOwner(admin1);
1482 
1483         verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1484                 eq(CALLER_USER_HANDLE), eq(false));
1485 
1486         dpm.clearProfileOwner(admin1);
1487 
1488         verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1489                 eq(CALLER_USER_HANDLE), eq(true));
1490     }
1491 
1492     @Test
testClearDeviceOwner_fromDifferentUser()1493     public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1494         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1495         mContext.callerPermissions.add(permission.MANAGE_USERS);
1496         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1497         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1498 
1499         // Set admin1 as a DA to the secondary user.
1500         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1501 
1502         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1503 
1504         // Set admin 1 as the DO to the system user.
1505 
1506         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1507         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1508         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1509         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
1510         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
1511 
1512         // Now call clear from the secondary user, which should throw.
1513         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1514 
1515         // Now call clear.
1516         getServices().addTestPackageUid(admin1.getPackageName(), DpmMockContext.CALLER_UID);
1517         assertExpectException(SecurityException.class,
1518                 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1519                 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
1520 
1521         // DO shouldn't be removed.
1522         assertThat(dpm.isDeviceManaged()).isTrue();
1523     }
1524 
1525     /**
1526      * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1527      *
1528      * Validates that when the device owner is removed, the reset password token is cleared
1529      */
1530     @Test
1531     @Ignore("b/277916462")
testClearDeviceOwner_clearResetPasswordToken()1532     public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1533         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1534         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1535         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1536 
1537         // Install admin1 on system user
1538         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1539 
1540         // Set admin1 to active admin and device owner
1541         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1542         dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM);
1543 
1544         // Add reset password token
1545         final long handle = 12000;
1546         final byte[] token = new byte[32];
1547         when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1548                 nullable(EscrowTokenStateChangeCallback.class)))
1549                 .thenReturn(handle);
1550         assertThat(dpm.setResetPasswordToken(admin1, token)).isTrue();
1551 
1552         // Assert reset password token is active
1553         when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1554                 eq(UserHandle.USER_SYSTEM)))
1555                 .thenReturn(true);
1556         assertThat(dpm.isResetPasswordTokenActive(admin1)).isTrue();
1557 
1558         // Remove the device owner
1559         dpm.clearDeviceOwnerApp(admin1.getPackageName());
1560 
1561         // Verify password reset password token was removed
1562         verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1563                 eq(UserHandle.USER_SYSTEM));
1564     }
1565 
1566     @Test
testSetProfileOwner()1567     public void testSetProfileOwner() throws Exception {
1568         setAsProfileOwner(admin1);
1569 
1570         // PO admin can't be deactivated.
1571         dpm.removeActiveAdmin(admin1);
1572         assertThat(dpm.isAdminActive(admin1)).isTrue();
1573 
1574         // Try setting DO on the same user, which should fail.
1575         setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1576         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1577         runAsCaller(mServiceContext, dpms, dpm -> {
1578             dpm.setActiveAdmin(admin2, /* refreshing= */ true, CALLER_USER_HANDLE);
1579             assertExpectException(IllegalStateException.class,
1580                     /* messageRegex= */ "already has a profile owner",
1581                     () -> dpm.setDeviceOwner(admin2, CALLER_USER_HANDLE));
1582         });
1583     }
1584 
1585     @Test
testClearProfileOwner()1586     public void testClearProfileOwner() throws Exception {
1587         setAsProfileOwner(admin1);
1588 
1589         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1590 
1591         assertThat(dpm.isProfileOwnerApp(admin1.getPackageName())).isTrue();
1592         assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse();
1593 
1594         // First try when the user is locked, which should fail.
1595         when(getServices().userManager.isUserUnlocked(anyInt()))
1596                 .thenReturn(false);
1597         assertExpectException(IllegalStateException.class,
1598                 /* messageRegex= */ "User must be running and unlocked",
1599                 () -> dpm.clearProfileOwner(admin1));
1600 
1601         // Clear, really.
1602         when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1603         dpm.clearProfileOwner(admin1);
1604 
1605         // Check
1606         assertThat(dpm.isProfileOwnerApp(admin1.getPackageName())).isFalse();
1607         assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse();
1608         verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1609                 null, CALLER_USER_HANDLE);
1610     }
1611 
1612     @Test
testSetProfileOwner_failures()1613     public void testSetProfileOwner_failures() throws Exception {
1614         // TODO Test more failure cases.  Basically test all chacks in enforceCanSetProfileOwner().
1615         // Package doesn't exist and caller is not system
1616         assertExpectException(SecurityException.class,
1617                 /* messageRegex= */ "Calling identity is not authorized",
1618                 () -> dpm.setProfileOwner(admin1, UserHandle.USER_SYSTEM));
1619 
1620         // Package exists, but caller is not system
1621         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1622         assertExpectException(SecurityException.class,
1623                 /* messageRegex= */ "Calling identity is not authorized",
1624                 () -> dpm.setProfileOwner(admin1, UserHandle.USER_SYSTEM));
1625     }
1626 
1627     @Test
testGetDeviceOwnerAdminLocked()1628     public void testGetDeviceOwnerAdminLocked() throws Exception {
1629         checkDeviceOwnerWithMultipleDeviceAdmins();
1630     }
1631 
1632     // This method is used primarily for testDeviceOwnerMigration.
checkDeviceOwnerWithMultipleDeviceAdmins()1633     private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1634         // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1635         // set admin3 on USER_SYSTEM as DO, then call getDeviceOwnerAdminLocked() to
1636         // make sure it gets the right component from the right user.
1637 
1638         final int ANOTHER_USER_ID = 100;
1639         final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1640 
1641         getServices().addUser(ANOTHER_USER_ID, 0, ""); // Add one more user.
1642 
1643         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1644         mContext.callerPermissions.add(permission.MANAGE_USERS);
1645         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1646         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1647 
1648         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1649 
1650         // Make sure the admin package is installed to each user.
1651         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1652         setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1653 
1654         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1655         setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1656 
1657         setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1658 
1659         // Set active admins to the users.
1660         dpm.setActiveAdmin(admin1, /* replace =*/ false);
1661         dpm.setActiveAdmin(admin3, /* replace =*/ false);
1662 
1663         dpm.setActiveAdmin(admin1, /* replace =*/ false, CALLER_USER_HANDLE);
1664         dpm.setActiveAdmin(admin2, /* replace =*/ false, CALLER_USER_HANDLE);
1665 
1666         dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1667 
1668         // Set DO on the system user which is only allowed during first boot.
1669         setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
1670         assertThat(dpm.setDeviceOwner(admin3, UserHandle.USER_SYSTEM)).isTrue();
1671         assertThat(dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)).isEqualTo(admin3);
1672 
1673         // Then check getDeviceOwnerAdminLocked().
1674         ActiveAdmin deviceOwner = getDeviceOwner();
1675         assertThat(deviceOwner.info.getComponent()).isEqualTo(admin3);
1676         assertThat(deviceOwner.getUid()).isEqualTo(DpmMockContext.CALLER_SYSTEM_USER_UID);
1677     }
1678 
1679     @Test
testSetGetApplicationRestriction()1680     public void testSetGetApplicationRestriction() {
1681         setAsProfileOwner(admin1);
1682         mContext.packageName = admin1.getPackageName();
1683 
1684         {
1685             Bundle rest = new Bundle();
1686             rest.putString("KEY_STRING", "Foo1");
1687             dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1688         }
1689 
1690         {
1691             Bundle rest = new Bundle();
1692             rest.putString("KEY_STRING", "Foo2");
1693             dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1694         }
1695 
1696         {
1697             Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1698             assertThat(returned).isNotNull();
1699             assertThat(returned.size()).isEqualTo(1);
1700             assertThat("Foo1").isEqualTo(returned.get("KEY_STRING"));
1701         }
1702 
1703         {
1704             Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1705             assertThat(returned).isNotNull();
1706             assertThat(returned.size()).isEqualTo(1);
1707             assertThat("Foo2").isEqualTo(returned.get("KEY_STRING"));
1708         }
1709 
1710         dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1711         assertThat(dpm.getApplicationRestrictions(admin1, "pkg2").size()).isEqualTo(0);
1712     }
1713 
1714     /**
1715      * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1716      * Useful for faking installed applications.
1717      *
1718      * @param packageName the name of the package to be setup
1719      * @param appId the application ID to be given to the package
1720      * @return the UID of the package as known by the mock package manager
1721      */
setupPackageInPackageManager(final String packageName, final int appId)1722     private int setupPackageInPackageManager(final String packageName, final int appId)
1723             throws Exception {
1724         return setupPackageInPackageManager(packageName, CALLER_USER_HANDLE, appId,
1725                 ApplicationInfo.FLAG_HAS_CODE);
1726     }
1727 
1728     /**
1729      * Setup a package in the package manager mock. Useful for faking installed applications.
1730      *
1731      * @param packageName the name of the package to be setup
1732      * @param userId the user id where the package will be "installed"
1733      * @param appId the application ID to be given to the package
1734      * @param flags flags to set in the ApplicationInfo for this package
1735      * @return the UID of the package as known by the mock package manager
1736      */
setupPackageInPackageManager(final String packageName, int userId, final int appId, int flags)1737     private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1738             int flags) throws Exception {
1739         final int uid = UserHandle.getUid(userId, appId);
1740         // Make the PackageManager return the package instead of throwing NameNotFoundException
1741         final PackageInfo pi = new PackageInfo();
1742         pi.applicationInfo = new ApplicationInfo();
1743         pi.applicationInfo.flags = flags;
1744         doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
1745                 eq(packageName),
1746                 longThat(flg -> (flg & PackageManager.MATCH_ANY_USER) == 0),
1747                 eq(userId));
1748         doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
1749                 eq(packageName),
1750                 longThat(flg -> (flg & PackageManager.MATCH_ANY_USER) != 0),
1751                 anyInt());
1752         doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
1753                 eq(packageName),
1754                 longThat(flg -> (flg & PackageManager.MATCH_ANY_USER) == 0),
1755                 eq(userId));
1756         doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
1757                 eq(packageName),
1758                 longThat(flg -> (flg & PackageManager.MATCH_ANY_USER) != 0),
1759                 anyInt());
1760         doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
1761         // Setup application UID with the PackageManager
1762         getServices().addTestPackageUid(packageName, uid);
1763         // Associate packageName to uid
1764         doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
1765         doReturn(new String[]{packageName})
1766                 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
1767         return uid;
1768     }
1769 
1770     @Test
testCertificateDisclosure()1771     public void testCertificateDisclosure() throws Exception {
1772         final int userId = CALLER_USER_HANDLE;
1773         final UserHandle user = UserHandle.of(userId);
1774 
1775         mServiceContext.packageName = mRealTestContext.getPackageName();
1776         mServiceContext.applicationInfo = new ApplicationInfo();
1777         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1778         when(mContext.resources.getColor(anyInt(), any())).thenReturn(Color.WHITE);
1779 
1780         StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1781         StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
1782 
1783         // Given that we have exactly one certificate installed,
1784         when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1785         // when that certificate is approved,
1786         dpms.approveCaCert(oneCert.getList().get(0), userId, true);
1787         // a notification should not be shown.
1788         verify(getServices().notificationManager, timeout(1000))
1789                 .cancelAsUser(anyString(), anyInt(), eq(user));
1790 
1791         // Given that we have four certificates installed,
1792         when(getServices().keyChainConnection.getService().getUserCaAliases())
1793                 .thenReturn(fourCerts);
1794         // when two of them are approved (one of them approved twice hence no action),
1795         dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1796         dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
1797         // a notification should be shown saying that there are two certificates left to approve.
1798         final String TEST_STRING_RESULT = "Test for exactly 2 certs out of 4";
1799         verify(getServices().notificationManager, timeout(1000))
1800                 .notifyAsUser(anyString(), anyInt(), argThat(hasExtra(EXTRA_TITLE,
1801                         TEST_STRING_RESULT
1802                 )), eq(user));
1803     }
1804 
1805     @Test
testRemoveCredentialManagementApp()1806     public void testRemoveCredentialManagementApp() throws Exception {
1807         final String packageName = "com.test.cred.mng";
1808         Intent intent = new Intent(Intent.ACTION_PACKAGE_REMOVED);
1809         intent.setData(Uri.parse("package:" + packageName));
1810         dpms.mReceiver.setPendingResult(
1811                 new BroadcastReceiver.PendingResult(Activity.RESULT_OK,
1812                         "resultData",
1813                         /* resultExtras= */ null,
1814                         BroadcastReceiver.PendingResult.TYPE_UNREGISTERED,
1815                         /* ordered= */ true,
1816                         /* sticky= */ false,
1817                         /* token= */ null,
1818                         CALLER_USER_HANDLE,
1819                         /* flags= */ 0));
1820         when(getServices().keyChainConnection.getService().hasCredentialManagementApp())
1821                 .thenReturn(true);
1822         when(getServices().keyChainConnection.getService().getCredentialManagementAppPackageName())
1823                 .thenReturn(packageName);
1824 
1825         dpms.mReceiver.onReceive(mContext, intent);
1826 
1827         flushTasks(dpms);
1828         verify(getServices().keyChainConnection.getService()).hasCredentialManagementApp();
1829         verify(getServices().keyChainConnection.getService()).removeCredentialManagementApp();
1830     }
1831 
1832     /**
1833      * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1834      * privileges can acually be exercised by a delegate are not covered here.
1835      */
1836     @Test
1837     @Ignore // temp dsiabled - broken with flags
testDelegation()1838     public void testDelegation() throws Exception {
1839         setAsProfileOwner(admin1);
1840 
1841         final int userHandle = CALLER_USER_HANDLE;
1842 
1843         // Given two packages
1844         final String CERT_DELEGATE = "com.delegate.certs";
1845         final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1846         final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1847         final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1848                 20989);
1849 
1850         // On delegation
1851         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1852         mContext.packageName = admin1.getPackageName();
1853         dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1854         dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1855 
1856         // DPMS correctly stores and retrieves the delegates
1857         DevicePolicyData policy = dpms.mUserData.get(userHandle);
1858         assertThat(policy.mDelegationMap.size()).isEqualTo(2);
1859         MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1860             DELEGATION_CERT_INSTALL);
1861         MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1862             DELEGATION_CERT_INSTALL);
1863         assertThat(dpm.getCertInstallerPackage(admin1)).isEqualTo(CERT_DELEGATE);
1864         MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1865             DELEGATION_APP_RESTRICTIONS);
1866         MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1867             DELEGATION_APP_RESTRICTIONS);
1868         assertThat(dpm.getApplicationRestrictionsManagingPackage(admin1))
1869                 .isEqualTo(RESTRICTIONS_DELEGATE);
1870 
1871         // On calling install certificate APIs from an unauthorized process
1872         mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1873         mContext.packageName = RESTRICTIONS_DELEGATE;
1874 
1875         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1876                 () -> dpm.installCaCert(null, null));
1877 
1878         // On calling install certificate APIs from an authorized process
1879         mContext.binder.callingUid = CERT_DELEGATE_UID;
1880         mContext.packageName = CERT_DELEGATE;
1881 
1882         // DPMS executes without a SecurityException
1883         try {
1884             dpm.installCaCert(null, null);
1885         } catch (SecurityException unexpected) {
1886             fail("Threw SecurityException on authorized access");
1887         } catch (NullPointerException expected) {
1888         }
1889 
1890         // On removing a delegate
1891         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1892         mContext.packageName = admin1.getPackageName();
1893         dpm.setCertInstallerPackage(admin1, null);
1894 
1895         // DPMS does not allow access to ex-delegate
1896         mContext.binder.callingUid = CERT_DELEGATE_UID;
1897         mContext.packageName = CERT_DELEGATE;
1898         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1899                 () -> dpm.installCaCert(null, null));
1900 
1901         // But still allows access to other existing delegates
1902         mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1903         mContext.packageName = RESTRICTIONS_DELEGATE;
1904         try {
1905             dpm.getApplicationRestrictions(null, "pkg");
1906         } catch (SecurityException expected) {
1907             fail("Threw SecurityException on authorized access");
1908         }
1909     }
1910 
1911     @Test
1912     @Ignore // Temp disabled - broken with flags
testApplicationRestrictionsManagingApp()1913     public void testApplicationRestrictionsManagingApp() throws Exception {
1914         setAsProfileOwner(admin1);
1915 
1916         final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
1917         final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1918         final String nonDelegateExceptionMessageRegex =
1919                 "Caller with uid \\d+ is not com.google.app.restrictions.manager";
1920         final int appRestrictionsManagerAppId = 20987;
1921         final int appRestrictionsManagerUid = setupPackageInPackageManager(
1922                 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
1923 
1924         // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1925         // delegated that permission yet.
1926         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1927         mContext.packageName = admin1.getPackageName();
1928         assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isFalse();
1929         final Bundle rest = new Bundle();
1930         rest.putString("KEY_STRING", "Foo1");
1931         assertExpectException(SecurityException.class, INVALID_CALLING_IDENTITY_MSG,
1932                 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
1933 
1934         // Check via the profile owner that no restrictions were set.
1935         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1936         mContext.packageName = admin1.getPackageName();
1937         assertThat(dpm.getApplicationRestrictions(admin1, "pkg1").size()).isEqualTo(0);
1938 
1939         // Check the API does not allow setting a non-existent package
1940         assertExpectException(PackageManager.NameNotFoundException.class,
1941                 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1942                 () -> dpm.setApplicationRestrictionsManagingPackage(
1943                         admin1, nonExistAppRestrictionsManagerPackage));
1944 
1945         // Let appRestrictionsManagerPackage manage app restrictions
1946         dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1947         assertThat(dpm.getApplicationRestrictionsManagingPackage(admin1))
1948                 .isEqualTo(appRestrictionsManagerPackage);
1949 
1950         // Now that package should be able to set and retrieve app restrictions.
1951         mContext.binder.callingUid = appRestrictionsManagerUid;
1952         mContext.packageName = appRestrictionsManagerPackage;
1953         assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isTrue();
1954         dpm.setApplicationRestrictions(null, "pkg1", rest);
1955         Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1956         assertThat(returned.size()).isEqualTo(1);
1957         assertThat(returned.get("KEY_STRING")).isEqualTo("Foo1");
1958 
1959         // The same app running on a separate user shouldn't be able to manage app restrictions.
1960         mContext.binder.callingUid = UserHandle.getUid(
1961                 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1962         assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isFalse();
1963         assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1964                 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
1965 
1966         // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1967         // too.
1968         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1969         mContext.packageName = admin1.getPackageName();
1970         assertThat(dpm.getApplicationRestrictions(admin1, "pkg1")).isEqualTo(returned);
1971         dpm.setApplicationRestrictions(admin1, "pkg1", null);
1972         assertThat(dpm.getApplicationRestrictions(admin1, "pkg1").size()).isEqualTo(0);
1973 
1974         // Removing the ability for the package to manage app restrictions.
1975         dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1976         assertThat(dpm.getApplicationRestrictionsManagingPackage(admin1)).isNull();
1977         mContext.binder.callingUid = appRestrictionsManagerUid;
1978         mContext.packageName = appRestrictionsManagerPackage;
1979         assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isFalse();
1980         assertExpectException(SecurityException.class, INVALID_CALLING_IDENTITY_MSG,
1981                 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
1982     }
1983 
1984     @Test
1985     @Ignore("b/277916462")
testSetUserRestriction_asDo()1986     public void testSetUserRestriction_asDo() throws Exception {
1987         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1988         mContext.callerPermissions.add(permission.MANAGE_USERS);
1989         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1990         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1991 
1992         // First, set DO.
1993 
1994         // Call from a process on the system user.
1995         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1996 
1997         // Make sure admin1 is installed on system user.
1998         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1999 
2000         // Call.
2001         dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2002         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
2003 
2004         assertNoDeviceOwnerRestrictions();
2005         reset(getServices().userManagerInternal);
2006 
2007         dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
2008         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2009                 eq(UserHandle.USER_SYSTEM),
2010                 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
2011                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
2012         reset(getServices().userManagerInternal);
2013 
2014         dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
2015         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2016                 eq(UserHandle.USER_SYSTEM),
2017                 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
2018                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM,
2019                         UserManager.DISALLOW_OUTGOING_CALLS),
2020                 eq(true));
2021         reset(getServices().userManagerInternal);
2022 
2023         DpmTestUtils.assertRestrictions(
2024                 DpmTestUtils.newRestrictions(
2025                         UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
2026                 getDeviceOwner().ensureUserRestrictions()
2027         );
2028         DpmTestUtils.assertRestrictions(
2029                 DpmTestUtils.newRestrictions(
2030                         UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
2031                 dpm.getUserRestrictions(admin1)
2032         );
2033 
2034         dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
2035         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2036                 eq(UserHandle.USER_SYSTEM),
2037                 MockUtils.checkUserRestrictions(),
2038                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM,
2039                         UserManager.DISALLOW_OUTGOING_CALLS),
2040                 eq(true));
2041         reset(getServices().userManagerInternal);
2042 
2043         DpmTestUtils.assertRestrictions(
2044                 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
2045                 getDeviceOwner().ensureUserRestrictions()
2046         );
2047         DpmTestUtils.assertRestrictions(
2048                 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
2049                 dpm.getUserRestrictions(admin1)
2050         );
2051 
2052         dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
2053         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2054                 eq(UserHandle.USER_SYSTEM),
2055                 MockUtils.checkUserRestrictions(),
2056                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
2057         reset(getServices().userManagerInternal);
2058 
2059         assertNoDeviceOwnerRestrictions();
2060 
2061         // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
2062         // DO sets them, the scope is global.
2063         dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
2064         reset(getServices().userManagerInternal);
2065         dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
2066         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2067                 eq(UserHandle.USER_SYSTEM),
2068                 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
2069                         UserManager.DISALLOW_UNMUTE_MICROPHONE),
2070                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
2071         reset(getServices().userManagerInternal);
2072 
2073         dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
2074         dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
2075         reset(getServices().userManagerInternal);
2076 
2077         // More tests.
2078         dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
2079         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2080                 eq(UserHandle.USER_SYSTEM),
2081                 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
2082                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
2083         reset(getServices().userManagerInternal);
2084 
2085         dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
2086         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2087                 eq(UserHandle.USER_SYSTEM),
2088                 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
2089                         UserManager.DISALLOW_ADD_USER),
2090                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
2091         reset(getServices().userManagerInternal);
2092 
2093         dpm.setCameraDisabled(admin1, true);
2094         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2095                 eq(UserHandle.USER_SYSTEM),
2096                 // DISALLOW_CAMERA will be applied globally.
2097                 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
2098                         UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_CAMERA),
2099                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
2100         reset(getServices().userManagerInternal);
2101     }
2102 
getDeviceOwner()2103     private ActiveAdmin getDeviceOwner() {
2104         ComponentName component = dpms.mOwners.getDeviceOwnerComponent();
2105         DevicePolicyData policy =
2106                 dpms.getUserData(dpms.mOwners.getDeviceOwnerUserId());
2107         for (ActiveAdmin admin : policy.mAdminList) {
2108             if (component.equals(admin.info.getComponent())) {
2109                 return admin;
2110             }
2111         }
2112         return null;
2113     }
2114 
2115     @Test
testDaDisallowedPolicies_SecurityException()2116     public void testDaDisallowedPolicies_SecurityException() throws Exception {
2117         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2118         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2119 
2120         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID, null,
2121                 Build.VERSION_CODES.Q);
2122         dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2123 
2124 
2125         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2126         boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
2127         assertExpectException(SecurityException.class, /* messageRegex= */ null,
2128                 () -> dpm.setCameraDisabled(admin1, true));
2129         assertThat(dpm.getCameraDisabled(admin1)).isEqualTo(originalCameraDisabled);
2130 
2131         int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
2132         assertExpectException(SecurityException.class, /* messageRegex= */ null,
2133                 () -> dpm.setKeyguardDisabledFeatures(admin1,
2134                         DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
2135         assertThat(dpm.getKeyguardDisabledFeatures(admin1))
2136                 .isEqualTo(originalKeyguardDisabledFeatures);
2137 
2138         long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
2139         assertExpectException(SecurityException.class, /* messageRegex= */ null,
2140                 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
2141         assertThat(dpm.getPasswordExpirationTimeout(admin1))
2142                 .isEqualTo(originalPasswordExpirationTimeout);
2143 
2144         if (isDeprecatedPasswordApisSupported()) {
2145             int originalPasswordQuality = dpm.getPasswordQuality(admin1);
2146             assertExpectException(SecurityException.class, /* messageRegex= */ null,
2147                     () -> dpm.setPasswordQuality(admin1,
2148                             DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
2149             assertThat(dpm.getPasswordQuality(admin1)).isEqualTo(originalPasswordQuality);
2150         }
2151     }
2152 
2153     @Test
2154     @Ignore("b/277916462")
testSetUserRestriction_asPo()2155     public void testSetUserRestriction_asPo() {
2156         setAsProfileOwner(admin1);
2157 
2158         DpmTestUtils.assertRestrictions(
2159                 DpmTestUtils.newRestrictions(),
2160                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE).ensureUserRestrictions()
2161         );
2162 
2163         dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
2164         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2165                 eq(CALLER_USER_HANDLE),
2166                 MockUtils.checkUserRestrictions(),
2167                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE,
2168                         UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
2169                 eq(false));
2170 
2171         dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
2172         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2173                 eq(CALLER_USER_HANDLE),
2174                 MockUtils.checkUserRestrictions(),
2175                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE,
2176                         UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
2177                         UserManager.DISALLOW_OUTGOING_CALLS),
2178                 eq(false));
2179 
2180         DpmTestUtils.assertRestrictions(
2181                 DpmTestUtils.newRestrictions(
2182                         UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
2183                         UserManager.DISALLOW_OUTGOING_CALLS
2184                 ),
2185                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2186                         .ensureUserRestrictions()
2187         );
2188         DpmTestUtils.assertRestrictions(
2189                 DpmTestUtils.newRestrictions(
2190                         UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
2191                         UserManager.DISALLOW_OUTGOING_CALLS
2192                 ),
2193                 dpm.getUserRestrictions(admin1)
2194         );
2195 
2196         dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
2197         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2198                 eq(CALLER_USER_HANDLE),
2199                 MockUtils.checkUserRestrictions(),
2200                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE,
2201                         UserManager.DISALLOW_OUTGOING_CALLS),
2202                 eq(false));
2203 
2204         DpmTestUtils.assertRestrictions(
2205                 DpmTestUtils.newRestrictions(
2206                         UserManager.DISALLOW_OUTGOING_CALLS
2207                 ),
2208                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2209                         .ensureUserRestrictions()
2210         );
2211         DpmTestUtils.assertRestrictions(
2212                 DpmTestUtils.newRestrictions(
2213                         UserManager.DISALLOW_OUTGOING_CALLS
2214                 ),
2215                 dpm.getUserRestrictions(admin1)
2216         );
2217 
2218         dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
2219         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2220                 eq(CALLER_USER_HANDLE),
2221                 MockUtils.checkUserRestrictions(),
2222                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE), eq(false));
2223 
2224         DpmTestUtils.assertRestrictions(
2225                 DpmTestUtils.newRestrictions(),
2226                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2227                         .ensureUserRestrictions()
2228         );
2229         DpmTestUtils.assertRestrictions(
2230                 DpmTestUtils.newRestrictions(),
2231                 dpm.getUserRestrictions(admin1)
2232         );
2233 
2234         // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
2235         // though when DO sets them they'll be applied globally.
2236         dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
2237 
2238         dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
2239         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2240                 eq(CALLER_USER_HANDLE),
2241                 MockUtils.checkUserRestrictions(),
2242                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE,
2243                         UserManager.DISALLOW_ADJUST_VOLUME,
2244                         UserManager.DISALLOW_UNMUTE_MICROPHONE),
2245                 eq(false));
2246 
2247         dpm.setCameraDisabled(admin1, true);
2248         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2249                 eq(CALLER_USER_HANDLE),
2250                 MockUtils.checkUserRestrictions(),
2251                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE,
2252                         UserManager.DISALLOW_ADJUST_VOLUME,
2253                         UserManager.DISALLOW_UNMUTE_MICROPHONE,
2254                         UserManager.DISALLOW_CAMERA),
2255                 eq(false));
2256         reset(getServices().userManagerInternal);
2257 
2258         // TODO Make sure restrictions are written to the file.
2259     }
2260 
2261     private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS =
2262             Sets.newSet(
2263                     UserManager.DISALLOW_AIRPLANE_MODE,
2264                     UserManager.DISALLOW_CONFIG_DATE_TIME,
2265                     UserManager.DISALLOW_CONFIG_PRIVATE_DNS
2266             );
2267 
2268     private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS =
2269             Sets.newSet(
2270                     UserManager.DISALLOW_CONFIG_BLUETOOTH,
2271                     UserManager.DISALLOW_CONFIG_LOCATION,
2272                     UserManager.DISALLOW_CONFIG_WIFI,
2273                     UserManager.DISALLOW_CONTENT_CAPTURE,
2274                     UserManager.DISALLOW_CONTENT_SUGGESTIONS,
2275                     UserManager.DISALLOW_DEBUGGING_FEATURES,
2276                     UserManager.DISALLOW_SHARE_LOCATION,
2277                     UserManager.DISALLOW_OUTGOING_CALLS,
2278                     UserManager.DISALLOW_BLUETOOTH_SHARING,
2279                     UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
2280                     UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
2281                     UserManager.DISALLOW_CONFIG_TETHERING,
2282                     UserManager.DISALLOW_DATA_ROAMING,
2283                     UserManager.DISALLOW_SAFE_BOOT,
2284                     UserManager.DISALLOW_SMS,
2285                     UserManager.DISALLOW_USB_FILE_TRANSFER,
2286                     UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
2287                     UserManager.DISALLOW_UNMUTE_MICROPHONE
2288             );
2289 
2290     @Test
2291     @Ignore("b/277916462")
testSetUserRestriction_asPoOfOrgOwnedDevice()2292     public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception {
2293         final int MANAGED_PROFILE_ADMIN_UID =
2294                 UserHandle.getUid(CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
2295         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2296 
2297         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2298         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
2299 
2300         when(getServices().userManager.getProfileParent(CALLER_USER_HANDLE))
2301                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
2302 
2303         for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS) {
2304             addAndRemoveGlobalUserRestrictionOnParentDpm(restriction);
2305         }
2306         for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS) {
2307             addAndRemoveLocalUserRestrictionOnParentDpm(restriction);
2308         }
2309 
2310         parentDpm.setCameraDisabled(admin1, true);
2311         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2312                 eq(CALLER_USER_HANDLE),
2313                 MockUtils.checkUserRestrictions(),
2314                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM,
2315                         UserManager.DISALLOW_CAMERA),
2316                 eq(false));
2317         DpmTestUtils.assertRestrictions(
2318                 DpmTestUtils.newRestrictions(UserManager.DISALLOW_CAMERA),
2319                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2320                         .getParentActiveAdmin()
2321                         .getEffectiveRestrictions()
2322         );
2323 
2324         parentDpm.setCameraDisabled(admin1, false);
2325         DpmTestUtils.assertRestrictions(
2326                 DpmTestUtils.newRestrictions(),
2327                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2328                         .getParentActiveAdmin()
2329                         .getEffectiveRestrictions()
2330         );
2331         reset(getServices().userManagerInternal);
2332     }
2333 
addAndRemoveGlobalUserRestrictionOnParentDpm(String restriction)2334     private void addAndRemoveGlobalUserRestrictionOnParentDpm(String restriction) {
2335         parentDpm.addUserRestriction(admin1, restriction);
2336         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2337                 eq(CALLER_USER_HANDLE),
2338                 MockUtils.checkUserRestrictions(restriction),
2339                 MockUtils.checkUserRestrictions(CALLER_USER_HANDLE),
2340                 eq(false));
2341         parentDpm.clearUserRestriction(admin1, restriction);
2342         DpmTestUtils.assertRestrictions(
2343                 DpmTestUtils.newRestrictions(),
2344                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2345                         .getParentActiveAdmin()
2346                         .getEffectiveRestrictions()
2347         );
2348     }
2349 
addAndRemoveLocalUserRestrictionOnParentDpm(String restriction)2350     private void addAndRemoveLocalUserRestrictionOnParentDpm(String restriction) {
2351         parentDpm.addUserRestriction(admin1, restriction);
2352         verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2353                 eq(CALLER_USER_HANDLE),
2354                 MockUtils.checkUserRestrictions(),
2355                 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM, restriction),
2356                 eq(false));
2357         parentDpm.clearUserRestriction(admin1, restriction);
2358         DpmTestUtils.assertRestrictions(
2359                 DpmTestUtils.newRestrictions(),
2360                 dpms.getProfileOwnerAdminLocked(CALLER_USER_HANDLE)
2361                         .getParentActiveAdmin()
2362                         .getEffectiveRestrictions()
2363         );
2364     }
2365 
2366     @Test
2367     @Ignore("b/277916462")
testNoDefaultEnabledUserRestrictions()2368     public void testNoDefaultEnabledUserRestrictions() throws Exception {
2369         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2370         mContext.callerPermissions.add(permission.MANAGE_USERS);
2371         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2372         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2373 
2374         // First, set DO.
2375 
2376         // Call from a process on the system user.
2377         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2378 
2379         // Make sure admin1 is installed on system user.
2380         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2381 
2382         dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2383         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
2384 
2385         assertNoDeviceOwnerRestrictions();
2386 
2387         reset(getServices().userManagerInternal);
2388 
2389         // Ensure the DISALLOW_REMOVE_MANAGED_PROFILES restriction doesn't show up as a
2390         // restriction to the device owner.
2391         dpm.addUserRestriction(admin1, UserManager.DISALLOW_REMOVE_MANAGED_PROFILE);
2392         assertNoDeviceOwnerRestrictions();
2393     }
2394 
assertNoDeviceOwnerRestrictions()2395     private void assertNoDeviceOwnerRestrictions() {
2396         DpmTestUtils.assertRestrictions(
2397                 DpmTestUtils.newRestrictions(),
2398                 getDeviceOwner().getEffectiveRestrictions()
2399         );
2400     }
2401 
2402     @Test
testSetFactoryResetProtectionPolicyWithDO()2403     public void testSetFactoryResetProtectionPolicyWithDO() throws Exception {
2404         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2405         setupDeviceOwner();
2406 
2407         when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2408                 DpmMockContext.CALLER_UID);
2409 
2410         FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2411                 .setFactoryResetProtectionAccounts(new ArrayList<>())
2412                 .setFactoryResetProtectionEnabled(false)
2413                 .build();
2414         dpm.setFactoryResetProtectionPolicy(admin1, policy);
2415 
2416         FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2417         assertThat(result).isEqualTo(policy);
2418         assertPoliciesAreEqual(policy, result);
2419 
2420         verify(mContext.spiedContext).sendBroadcastAsUser(
2421                 MockUtils.checkIntentAction(
2422                         DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2423                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
2424                 eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION));
2425     }
2426 
2427     @Test
testSetFactoryResetProtectionPolicyFailWithPO()2428     public void testSetFactoryResetProtectionPolicyFailWithPO() throws Exception {
2429         setupProfileOwner();
2430 
2431         FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2432                 .setFactoryResetProtectionEnabled(false)
2433                 .build();
2434 
2435         assertExpectException(SecurityException.class, null,
2436                 () -> dpm.setFactoryResetProtectionPolicy(admin1, policy));
2437     }
2438 
2439     @Test
testSetFactoryResetProtectionPolicyWithPOOfOrganizationOwnedDevice()2440     public void testSetFactoryResetProtectionPolicyWithPOOfOrganizationOwnedDevice()
2441             throws Exception {
2442         setupProfileOwner();
2443         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
2444 
2445         when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2446                 DpmMockContext.CALLER_UID);
2447 
2448         List<String> accounts = new ArrayList<>();
2449         accounts.add("Account 1");
2450         accounts.add("Account 2");
2451 
2452         FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2453                 .setFactoryResetProtectionAccounts(accounts)
2454                 .build();
2455 
2456         dpm.setFactoryResetProtectionPolicy(admin1, policy);
2457 
2458         FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2459         assertThat(result).isEqualTo(policy);
2460         assertPoliciesAreEqual(policy, result);
2461 
2462         verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
2463                 MockUtils.checkIntentAction(
2464                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
2465                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
2466                 eq(null),
2467                 any(Bundle.class));
2468         verify(mContext.spiedContext).sendBroadcastAsUser(
2469                 MockUtils.checkIntentAction(
2470                         DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED),
2471                 MockUtils.checkUserHandle(CALLER_USER_HANDLE));
2472         verify(mContext.spiedContext).sendBroadcastAsUser(
2473                 MockUtils.checkIntentAction(
2474                         DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2475                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
2476                 eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION));
2477     }
2478 
2479     @Test
testGetFactoryResetProtectionPolicyWithFrpManagementAgent()2480     public void testGetFactoryResetProtectionPolicyWithFrpManagementAgent()
2481             throws Exception {
2482         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2483         setupDeviceOwner();
2484         when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2485                 DpmMockContext.CALLER_UID);
2486 
2487         FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2488                 .setFactoryResetProtectionAccounts(new ArrayList<>())
2489                 .setFactoryResetProtectionEnabled(false)
2490                 .build();
2491 
2492         dpm.setFactoryResetProtectionPolicy(admin1, policy);
2493 
2494         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2495         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2496         dpm.setActiveAdmin(admin1, /*replace=*/ false);
2497         FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(null);
2498         assertThat(result).isEqualTo(policy);
2499         assertPoliciesAreEqual(policy, result);
2500 
2501         verify(mContext.spiedContext).sendBroadcastAsUser(
2502                 MockUtils.checkIntentAction(
2503                         DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2504                 MockUtils.checkUserHandle(CALLER_USER_HANDLE),
2505                 eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION));
2506     }
2507 
assertPoliciesAreEqual(FactoryResetProtectionPolicy expectedPolicy, FactoryResetProtectionPolicy actualPolicy)2508     private void assertPoliciesAreEqual(FactoryResetProtectionPolicy expectedPolicy,
2509             FactoryResetProtectionPolicy actualPolicy) {
2510         assertThat(actualPolicy.isFactoryResetProtectionEnabled()).isEqualTo(
2511                 expectedPolicy.isFactoryResetProtectionEnabled());
2512         assertAccountsAreEqual(expectedPolicy.getFactoryResetProtectionAccounts(),
2513                 actualPolicy.getFactoryResetProtectionAccounts());
2514     }
2515 
assertAccountsAreEqual(List<String> expectedAccounts, List<String> actualAccounts)2516     private void assertAccountsAreEqual(List<String> expectedAccounts,
2517             List<String> actualAccounts) {
2518         assertThat(actualAccounts).containsExactlyElementsIn(expectedAccounts);
2519     }
2520 
2521     @Test
testSetPermittedInputMethodsWithPOOfOrganizationOwnedDevice()2522     public void testSetPermittedInputMethodsWithPOOfOrganizationOwnedDevice()
2523             throws Exception {
2524         String packageName = "com.google.pkg.one";
2525         setupProfileOwner();
2526         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
2527 
2528         // Allow all input methods
2529         parentDpm.setPermittedInputMethods(admin1, null);
2530 
2531         assertThat(parentDpm.getPermittedInputMethods(admin1)).isNull();
2532 
2533         // Allow only system input methods
2534         parentDpm.setPermittedInputMethods(admin1, new ArrayList<>());
2535 
2536         assertThat(parentDpm.getPermittedInputMethods(admin1)).isEmpty();
2537 
2538         // Don't allow specific third party input methods
2539         final List<String> inputMethods = Collections.singletonList(packageName);
2540 
2541         assertExpectException(IllegalArgumentException.class, /* messageRegex= */ "Permitted "
2542                         + "input methods must allow all input methods or only system input methods "
2543                         + "when called on the parent instance of an organization-owned device",
2544                 () -> parentDpm.setPermittedInputMethods(admin1, inputMethods));
2545     }
2546 
2547     @Test
testGetProxyParameters()2548     public void testGetProxyParameters() throws Exception {
2549         assertThat(dpm.getProxyParameters(inetAddrProxy("192.0.2.1", 1234), emptyList()))
2550                 .isEqualTo(new Pair<>("192.0.2.1:1234", ""));
2551         assertThat(dpm.getProxyParameters(inetAddrProxy("192.0.2.1", 1234),
2552                 listOf("one.example.com  ", "  two.example.com ")))
2553                 .isEqualTo(new Pair<>("192.0.2.1:1234", "one.example.com,two.example.com"));
2554         assertThat(dpm.getProxyParameters(hostnameProxy("proxy.example.com", 1234), emptyList()))
2555                 .isEqualTo(new Pair<>("proxy.example.com:1234", ""));
2556         assertThat(dpm.getProxyParameters(hostnameProxy("proxy.example.com", 1234),
2557                 listOf("excluded.example.com")))
2558                 .isEqualTo(new Pair<>("proxy.example.com:1234", "excluded.example.com"));
2559 
2560         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2561                 inetAddrProxy("192.0.2.1", 0), emptyList()));
2562         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2563                 hostnameProxy("", 1234), emptyList()));
2564         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2565                 hostnameProxy("", 0), emptyList()));
2566         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2567                 hostnameProxy("invalid! hostname", 1234), emptyList()));
2568         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2569                 hostnameProxy("proxy.example.com", 1234), listOf("invalid exclusion")));
2570         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2571                 hostnameProxy("proxy.example.com", -1), emptyList()));
2572         assertThrows(IllegalArgumentException.class, () -> dpm.getProxyParameters(
2573                 hostnameProxy("proxy.example.com", 0xFFFF + 1), emptyList()));
2574     }
2575 
inetAddrProxy(String inetAddr, int port)2576     private static Proxy inetAddrProxy(String inetAddr, int port) {
2577         return new Proxy(
2578                 Proxy.Type.HTTP, new InetSocketAddress(parseNumericAddress(inetAddr), port));
2579     }
2580 
hostnameProxy(String hostname, int port)2581     private static Proxy hostnameProxy(String hostname, int port) {
2582         return new Proxy(
2583                 Proxy.Type.HTTP, InetSocketAddress.createUnresolved(hostname, port));
2584     }
2585 
listOf(String... args)2586     private static List<String> listOf(String... args) {
2587         return Arrays.asList(args);
2588     }
2589 
2590     @Test
testSetKeyguardDisabledFeaturesWithDO()2591     public void testSetKeyguardDisabledFeaturesWithDO() throws Exception {
2592         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2593         setupDeviceOwner();
2594 
2595         dpm.setKeyguardDisabledFeatures(admin1, DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2596 
2597         assertThat(dpm.getKeyguardDisabledFeatures(admin1)).isEqualTo(
2598                 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2599     }
2600 
2601     @Test
testSetKeyguardDisabledFeaturesWithPO()2602     public void testSetKeyguardDisabledFeaturesWithPO() throws Exception {
2603         setupProfileOwner();
2604 
2605         dpm.setKeyguardDisabledFeatures(admin1, DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT);
2606 
2607         assertThat(dpm.getKeyguardDisabledFeatures(admin1)).isEqualTo(
2608                 DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT);
2609     }
2610 
2611     @Test
testSetKeyguardDisabledFeaturesWithPOOfOrganizationOwnedDevice()2612     public void testSetKeyguardDisabledFeaturesWithPOOfOrganizationOwnedDevice()
2613             throws Exception {
2614         final int MANAGED_PROFILE_USER_ID = CALLER_USER_HANDLE;
2615         final int MANAGED_PROFILE_ADMIN_UID =
2616                 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2617         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2618 
2619         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2620         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
2621 
2622         parentDpm.setKeyguardDisabledFeatures(admin1,
2623                 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2624 
2625         assertThat(parentDpm.getKeyguardDisabledFeatures(admin1)).isEqualTo(
2626                 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2627     }
2628 
2629     @Test
2630     @Ignore("b/277916462")
testSetApplicationHiddenWithDO()2631     public void testSetApplicationHiddenWithDO() throws Exception {
2632         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2633         setupDeviceOwner();
2634         mContext.packageName = admin1.getPackageName();
2635         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2636         mockEmptyPolicyExemptApps();
2637 
2638         String packageName = "com.google.android.test";
2639 
2640         dpm.setApplicationHidden(admin1, packageName, true);
2641         verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2642                 true, UserHandle.USER_SYSTEM);
2643 
2644         dpm.setApplicationHidden(admin1, packageName, false);
2645         verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2646                 false, UserHandle.USER_SYSTEM);
2647 
2648         verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2649                 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
2650         verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2651                 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_SYSTEM_ONLY,
2652                 UserHandle.USER_SYSTEM);
2653     }
2654 
2655     @Test
2656     @Ignore("b/277916462")
testSetApplicationHiddenWithPOOfOrganizationOwnedDevice()2657     public void testSetApplicationHiddenWithPOOfOrganizationOwnedDevice() throws Exception {
2658         final int MANAGED_PROFILE_USER_ID = CALLER_USER_HANDLE;
2659         final int MANAGED_PROFILE_ADMIN_UID =
2660                 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2661         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2662 
2663         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2664         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
2665         mContext.packageName = admin1.getPackageName();
2666         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2667         mockEmptyPolicyExemptApps();
2668 
2669         String packageName = "com.google.android.test";
2670 
2671         ApplicationInfo applicationInfo = new ApplicationInfo();
2672         applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
2673         when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
2674                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
2675         when(getServices().ipackageManager.getApplicationInfo(packageName,
2676                 PackageManager.MATCH_UNINSTALLED_PACKAGES, UserHandle.USER_SYSTEM)).thenReturn(
2677                 applicationInfo);
2678 
2679         parentDpm.setApplicationHidden(admin1, packageName, true);
2680         verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2681                 true, UserHandle.USER_SYSTEM);
2682 
2683         parentDpm.setApplicationHidden(admin1, packageName, false);
2684         verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2685                 false, UserHandle.USER_SYSTEM);
2686     }
2687 
2688     @Test
testGetMacAddress()2689     public void testGetMacAddress() throws Exception {
2690         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2691         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2692         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2693 
2694         // In this test, change the caller user to "system".
2695         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2696 
2697         // Make sure admin1 is installed on system user.
2698         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2699 
2700         // Test 1. Caller doesn't have DO or DA.
2701         assertExpectException(SecurityException.class, /* messageRegex= */
2702                 "does not exist or is not owned by uid", () -> dpm.getWifiMacAddress(admin1));
2703 
2704         // DO needs to be an DA.
2705         dpm.setActiveAdmin(admin1, /* replace =*/ false);
2706         assertThat(dpm.isAdminActive(admin1)).isTrue();
2707 
2708         // Test 2. Caller has DA, but not DO.
2709         assertExpectException(SecurityException.class,
2710                 /* messageRegex= */ INVALID_CALLING_IDENTITY_MSG,
2711                 () -> dpm.getWifiMacAddress(admin1));
2712 
2713         // Test 3. Caller has PO, but not DO.
2714         assertThat(dpm.setProfileOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
2715         assertExpectException(SecurityException.class,
2716                 /* messageRegex= */ INVALID_CALLING_IDENTITY_MSG,
2717                 () -> dpm.getWifiMacAddress(admin1));
2718 
2719         // Remove PO.
2720         dpm.clearProfileOwner(admin1);
2721         dpm.setActiveAdmin(admin1, false);
2722         // Test 4, Caller is DO now.
2723         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
2724 
2725         // 4-1.  But WifiManager is not ready.
2726         assertThat(dpm.getWifiMacAddress(admin1)).isNull();
2727 
2728         // 4-2.  When WifiManager returns an empty array, dpm should also output null.
2729         when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
2730         assertThat(dpm.getWifiMacAddress(admin1)).isNull();
2731 
2732         // 4-3. With a real MAC address.
2733         final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2734         when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
2735         assertThat(dpm.getWifiMacAddress(admin1)).isEqualTo("11:22:33:44:55:66");
2736     }
2737 
2738     @Test
testGetMacAddressByOrgOwnedPO()2739     public void testGetMacAddressByOrgOwnedPO() throws Exception {
2740         setupProfileOwner();
2741         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
2742 
2743         final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2744         when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
2745         assertThat(dpm.getWifiMacAddress(admin1)).isEqualTo("11:22:33:44:55:66");
2746     }
2747 
2748     @Test
testReboot()2749     public void testReboot() throws Exception {
2750         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2751         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2752 
2753         // In this test, change the caller user to "system".
2754         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2755 
2756         // Make sure admin1 is installed on system user.
2757         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2758 
2759         // Set admin1 as DA.
2760         dpm.setActiveAdmin(admin1, false);
2761         assertThat(dpm.isAdminActive(admin1)).isTrue();
2762         assertExpectException(SecurityException.class, /* messageRegex= */
2763                 INVALID_CALLING_IDENTITY_MSG, () -> dpm.reboot(admin1));
2764 
2765         // Set admin1 as PO.
2766         assertThat(dpm.setProfileOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
2767         assertExpectException(SecurityException.class, /* messageRegex= */
2768                 INVALID_CALLING_IDENTITY_MSG, () -> dpm.reboot(admin1));
2769 
2770         // Remove PO and add DO.
2771         dpm.clearProfileOwner(admin1);
2772         dpm.setActiveAdmin(admin1, false);
2773         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
2774 
2775         // admin1 is DO.
2776         // Set current call state of device to ringing.
2777         when(getServices().telephonyManager.getCallState())
2778                 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
2779         assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2780                 () -> dpm.reboot(admin1));
2781 
2782         // Set current call state of device to dialing/active.
2783         when(getServices().telephonyManager.getCallState())
2784                 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
2785         assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2786                 () -> dpm.reboot(admin1));
2787 
2788         // Set current call state of device to idle.
2789         when(getServices().telephonyManager.getCallState())
2790                 .thenReturn(TelephonyManager.CALL_STATE_IDLE);
2791         dpm.reboot(admin1);
2792     }
2793 
2794     @Test
testSetGetSupportText()2795     public void testSetGetSupportText() {
2796         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2797         dpm.setActiveAdmin(admin1, true);
2798         dpm.setActiveAdmin(admin2, true);
2799         mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2800 
2801         // Null default support messages.
2802         {
2803             assertThat(dpm.getLongSupportMessage(admin1)).isNull();
2804             assertThat(dpm.getShortSupportMessage(admin1)).isNull();
2805             mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2806             assertThat(dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull();
2807             assertThat(dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull();
2808             mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2809         }
2810 
2811         // Only system can call the per user versions.
2812         {
2813             assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2814                     () -> dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE));
2815             assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2816                     () -> dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE));
2817         }
2818 
2819         // Can't set message for admin in another uid.
2820         {
2821             mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
2822             assertThrows(SecurityException.class,
2823                     () -> dpm.setShortSupportMessage(admin1, "Some text"));
2824             mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2825         }
2826 
2827         // Set/Get short returns what it sets and other admins text isn't changed.
2828         {
2829             final String supportText = "Some text to test with.";
2830             dpm.setShortSupportMessage(admin1, supportText);
2831             assertThat(dpm.getShortSupportMessage(admin1)).isEqualTo(supportText);
2832             assertThat(dpm.getLongSupportMessage(admin1)).isNull();
2833             assertThat(dpm.getShortSupportMessage(admin2)).isNull();
2834 
2835             mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2836             assertThat(dpm.getShortSupportMessageForUser(admin1,
2837             CALLER_USER_HANDLE)).isEqualTo(supportText);
2838             assertThat(dpm.getShortSupportMessageForUser(admin2, CALLER_USER_HANDLE)).isNull();
2839             assertThat(dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull();
2840             mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2841 
2842             dpm.setShortSupportMessage(admin1, null);
2843             assertThat(dpm.getShortSupportMessage(admin1)).isNull();
2844         }
2845 
2846         // Set/Get long returns what it sets and other admins text isn't changed.
2847         {
2848             final String supportText = "Some text to test with.\nWith more text.";
2849             dpm.setLongSupportMessage(admin1, supportText);
2850             assertThat(dpm.getLongSupportMessage(admin1)).isEqualTo(supportText);
2851             assertThat(dpm.getShortSupportMessage(admin1)).isNull();
2852             assertThat(dpm.getLongSupportMessage(admin2)).isNull();
2853 
2854             mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2855             assertThat(dpm.getLongSupportMessageForUser(admin1,
2856             CALLER_USER_HANDLE)).isEqualTo(supportText);
2857             assertThat(dpm.getLongSupportMessageForUser(admin2, CALLER_USER_HANDLE)).isNull();
2858             assertThat(dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull();
2859             mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2860 
2861             dpm.setLongSupportMessage(admin1, null);
2862             assertThat(dpm.getLongSupportMessage(admin1)).isNull();
2863         }
2864     }
2865 
2866     @Test
testSetGetMeteredDataDisabledPackages()2867     public void testSetGetMeteredDataDisabledPackages() throws Exception {
2868         setAsProfileOwner(admin1);
2869 
2870         assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEmpty();
2871 
2872         // Setup
2873         final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2874         final String package1 = "com.example.one";
2875         final String package2 = "com.example.two";
2876         pkgsToRestrict.add(package1);
2877         pkgsToRestrict.add(package2);
2878         setupPackageInPackageManager(package1, CALLER_USER_HANDLE, 123, 0);
2879         setupPackageInPackageManager(package2, CALLER_USER_HANDLE, 456, 0);
2880         List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
2881 
2882         // Verify
2883         assertThat(excludedPkgs).isEmpty();
2884         assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEqualTo(pkgsToRestrict);
2885         verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2886                 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2887                 eq(CALLER_USER_HANDLE));
2888 
2889         // Setup
2890         pkgsToRestrict.remove(package1);
2891         excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
2892 
2893         // Verify
2894         assertThat(excludedPkgs).isEmpty();
2895         assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEqualTo(pkgsToRestrict);
2896         verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2897                 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2898                 eq(CALLER_USER_HANDLE));
2899     }
2900 
2901     @Test
testSetMeteredDataDisabledPackagesExemptRoles()2902     public void testSetMeteredDataDisabledPackagesExemptRoles() throws Exception {
2903         // TODO(b/362545319): reference role name from role manager once it's exposed.
2904         final String controllerRole = "android.app.role.SYSTEM_FINANCED_DEVICE_CONTROLLER";
2905 
2906         setAsProfileOwner(admin1);
2907 
2908         assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEmpty();
2909 
2910         // Setup
2911         final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2912         final ArrayList<String> pkgsExpectedAsNotRestricted = new ArrayList<>();
2913         final String packageWithControllerRole = "com.example.controller";
2914         final String packageWithKioskRole = "com.example.kiosk";
2915         final String packageWithNotExemptRole = "com.example.notexempt";
2916 
2917         pkgsToRestrict.add(packageWithControllerRole);
2918         pkgsToRestrict.add(packageWithKioskRole);
2919         pkgsToRestrict.add(packageWithNotExemptRole);
2920 
2921         pkgsExpectedAsNotRestricted.add(packageWithControllerRole);
2922         pkgsExpectedAsNotRestricted.add(packageWithKioskRole);
2923 
2924         setupPackageInPackageManager(packageWithControllerRole, CALLER_USER_HANDLE, 123, 0);
2925         setupPackageInPackageManager(packageWithKioskRole, CALLER_USER_HANDLE, 456, 0);
2926         setupPackageInPackageManager(packageWithNotExemptRole, CALLER_USER_HANDLE, 789, 0);
2927 
2928         when(getServices().roleManagerForMock.getRoleHoldersAsUser(controllerRole,
2929                 UserHandle.of(CALLER_USER_HANDLE)))
2930                 .thenReturn(new ArrayList<>(Arrays.asList(packageWithControllerRole)));
2931         when(getServices().roleManagerForMock.getRoleHoldersAsUser(
2932                 RoleManager.ROLE_FINANCED_DEVICE_KIOSK,
2933                 UserHandle.of(CALLER_USER_HANDLE)))
2934                 .thenReturn(new ArrayList<>(Arrays.asList(packageWithKioskRole)));
2935 
2936         List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
2937 
2938         // Verify
2939         assertThat(excludedPkgs).containsExactlyElementsIn(pkgsExpectedAsNotRestricted);
2940         assertThat(dpm.getMeteredDataDisabledPackages(admin1))
2941                 .isEqualTo(Arrays.asList(packageWithNotExemptRole));
2942         verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2943                 MockUtils.checkApps(packageWithNotExemptRole),
2944                 eq(CALLER_USER_HANDLE));
2945     }
2946 
2947     @Test
testSetGetMeteredDataDisabledPackages_deviceAdmin()2948     public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
2949         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2950         dpm.setActiveAdmin(admin1, true);
2951         assertThat(dpm.isAdminActive(admin1)).isTrue();
2952         mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2953 
2954         assertExpectException(SecurityException.class,  /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2955                 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
2956         assertExpectException(SecurityException.class,  /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2957                 () -> dpm.getMeteredDataDisabledPackages(admin1));
2958     }
2959 
2960     @Test
testIsMeteredDataDisabledForUserPackage()2961     public void testIsMeteredDataDisabledForUserPackage() throws Exception {
2962         setAsProfileOwner(admin1);
2963 
2964         // Setup
2965         final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2966         final String package1 = "com.example.one";
2967         final String package2 = "com.example.two";
2968         final String package3 = "com.example.three";
2969         pkgsToRestrict.add(package1);
2970         pkgsToRestrict.add(package2);
2971         setupPackageInPackageManager(package1, CALLER_USER_HANDLE, 123, 0);
2972         setupPackageInPackageManager(package2, CALLER_USER_HANDLE, 456, 0);
2973         List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
2974 
2975         // Verify
2976         assertThat(excludedPkgs).isEmpty();
2977         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2978         assertWithMessage("%s should be restricted", package1)
2979                 .that(dpm.isMeteredDataDisabledPackageForUser(admin1, package1, CALLER_USER_HANDLE))
2980                 .isTrue();
2981         assertWithMessage("%s should be restricted", package2)
2982                 .that(dpm.isMeteredDataDisabledPackageForUser(admin1, package2, CALLER_USER_HANDLE))
2983                 .isTrue();
2984         assertWithMessage("%s should not be restricted", package3)
2985                 .that(dpm.isMeteredDataDisabledPackageForUser(admin1, package3, CALLER_USER_HANDLE))
2986                 .isFalse();
2987     }
2988 
2989     @Test
testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller()2990     public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
2991         setAsProfileOwner(admin1);
2992         assertExpectException(SecurityException.class,
2993                 /* messageRegex= */ "Only the system can query restricted pkgs",
2994                 () -> dpm.isMeteredDataDisabledPackageForUser(
2995                         admin1, "com.example.one", CALLER_USER_HANDLE));
2996         dpm.clearProfileOwner(admin1);
2997 
2998         setDeviceOwner();
2999         assertExpectException(SecurityException.class,
3000                 /* messageRegex= */ "Only the system can query restricted pkgs",
3001                 () -> dpm.isMeteredDataDisabledPackageForUser(
3002                         admin1, "com.example.one", CALLER_USER_HANDLE));
3003         clearDeviceOwner();
3004     }
3005 
3006     @Test
3007     @Ignore("b/277916462")
testCreateAdminSupportIntent()3008     public void testCreateAdminSupportIntent() throws Exception {
3009         // Setup device owner.
3010         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3011         setupDeviceOwner();
3012 
3013         // Nonexisting permission returns null
3014         Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
3015         assertThat(intent).isNull();
3016 
3017         // Existing permission that is not set returns null
3018         intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
3019         assertThat(intent).isNull();
3020 
3021         // Existing permission that is not set by device/profile owner returns null
3022         when(getServices().userManager.hasUserRestriction(
3023                 eq(UserManager.DISALLOW_ADJUST_VOLUME),
3024                 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3025                 .thenReturn(true);
3026         intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
3027         assertThat(intent).isNull();
3028 
3029         // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
3030         doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
3031                 new UserManager.EnforcingUser(
3032                         UserHandle.USER_SYSTEM,
3033                         UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
3034         ).when(getServices().userManager).getUserRestrictionSources(
3035                 eq(UserManager.DISALLOW_ADJUST_VOLUME),
3036                 eq(UserHandle.of(UserHandle.USER_SYSTEM)));
3037         intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
3038         assertThat(intent).isNotNull();
3039         assertThat(intent.getAction()).isEqualTo(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
3040         assertThat(intent.getIntExtra(Intent.EXTRA_USER_ID, -1))
3041                 .isEqualTo(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID));
3042         assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION))
3043                 .isEqualTo(UserManager.DISALLOW_ADJUST_VOLUME);
3044 
3045         // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
3046         // user restrictions
3047 
3048         // Camera is not disabled
3049         intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
3050         assertThat(intent).isNull();
3051 
3052         // Camera is disabled
3053         dpm.setCameraDisabled(admin1, true);
3054         intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
3055         assertThat(intent).isNotNull();
3056         assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION))
3057                 .isEqualTo(DevicePolicyManager.POLICY_DISABLE_CAMERA);
3058 
3059         // Screen capture is not disabled
3060         intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
3061         assertThat(intent).isNull();
3062 
3063         // Screen capture is disabled
3064         dpm.setScreenCaptureDisabled(admin1, true);
3065         intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
3066         assertThat(intent).isNotNull();
3067         assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION))
3068                 .isEqualTo(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
3069 
3070         // Same checks for different user
3071         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3072         // Camera should be disabled by device owner
3073         intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
3074         assertThat(intent).isNotNull();
3075         assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION))
3076                 .isEqualTo(DevicePolicyManager.POLICY_DISABLE_CAMERA);
3077         assertThat(intent.getIntExtra(Intent.EXTRA_USER_ID, -1))
3078                 .isEqualTo(UserHandle.getUserId(DpmMockContext.CALLER_UID));
3079         // ScreenCapture should not be disabled by device owner
3080         intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
3081         assertThat(intent).isNull();
3082     }
3083 
3084     /**
3085      * Test for:
3086      * {@link DevicePolicyManager#setAffiliationIds}
3087      * {@link DevicePolicyManager#getAffiliationIds}
3088      * {@link DevicePolicyManager#isAffiliatedUser}
3089      */
3090     @Test
testUserAffiliation()3091     public void testUserAffiliation() throws Exception {
3092         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
3093         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3094         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
3095         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
3096 
3097         // Check that the system user is unaffiliated.
3098         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3099         assertThat(dpm.isAffiliatedUser()).isFalse();
3100 
3101         // Set a device owner on the system user. Check that the system user becomes affiliated.
3102         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
3103         dpm.setActiveAdmin(admin1, /* replace =*/ false);
3104         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
3105         assertThat(dpm.isAffiliatedUser()).isTrue();
3106         assertThat(dpm.getAffiliationIds(admin1).isEmpty()).isTrue();
3107 
3108         // Install a profile owner. Check that the test user is unaffiliated.
3109         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3110         setAsProfileOwner(admin2);
3111         assertThat(dpm.isAffiliatedUser()).isFalse();
3112         assertThat(dpm.getAffiliationIds(admin2).isEmpty()).isTrue();
3113 
3114         // Have the profile owner specify a set of affiliation ids. Check that the test user remains
3115         // unaffiliated.
3116         final Set<String> userAffiliationIds = new ArraySet<>();
3117         userAffiliationIds.add("red");
3118         userAffiliationIds.add("green");
3119         userAffiliationIds.add("blue");
3120         dpm.setAffiliationIds(admin2, userAffiliationIds);
3121         MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
3122         assertThat(dpm.isAffiliatedUser()).isFalse();
3123 
3124         // Have the device owner specify a set of affiliation ids that do not intersect with those
3125         // specified by the profile owner. Check that the test user remains unaffiliated.
3126         final Set<String> deviceAffiliationIds = new ArraySet<>();
3127         deviceAffiliationIds.add("cyan");
3128         deviceAffiliationIds.add("yellow");
3129         deviceAffiliationIds.add("magenta");
3130         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3131         dpm.setAffiliationIds(admin1, deviceAffiliationIds);
3132         MoreAsserts.assertContentsInAnyOrder(
3133             dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
3134         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3135         assertThat(dpm.isAffiliatedUser()).isFalse();
3136 
3137         // Have the profile owner specify a set of affiliation ids that intersect with those
3138         // specified by the device owner. Check that the test user becomes affiliated.
3139         userAffiliationIds.add("yellow");
3140         dpm.setAffiliationIds(admin2, userAffiliationIds);
3141         MoreAsserts.assertContentsInAnyOrder(
3142             dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
3143         assertThat(dpm.isAffiliatedUser()).isTrue();
3144 
3145         // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
3146         dpm.setAffiliationIds(admin2, Collections.emptySet());
3147         assertThat(dpm.getAffiliationIds(admin2).isEmpty()).isTrue();
3148         assertThat(dpm.isAffiliatedUser()).isFalse();
3149 
3150         // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
3151         dpm.setAffiliationIds(admin2, userAffiliationIds);
3152         assertThat(dpm.isAffiliatedUser()).isTrue();
3153         dpm.clearProfileOwner(admin2);
3154         assertThat(dpm.isAffiliatedUser()).isFalse();
3155 
3156         // Check that the system user remains affiliated.
3157         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3158         assertThat(dpm.isAffiliatedUser()).isTrue();
3159 
3160         // Clear the device owner - the user becomes unaffiliated.
3161         clearDeviceOwner();
3162         assertThat(dpm.isAffiliatedUser()).isFalse();
3163     }
3164 
3165     @Test
testGetUserProvisioningState_defaultResult()3166     public void testGetUserProvisioningState_defaultResult() {
3167         mContext.callerPermissions.add(permission.MANAGE_USERS);
3168         assertThat(dpm.getUserProvisioningState())
3169                 .isEqualTo(DevicePolicyManager.STATE_USER_UNMANAGED);
3170     }
3171 
3172     @Test
testSetUserProvisioningState_permission()3173     public void testSetUserProvisioningState_permission() throws Exception {
3174         setupProfileOwner();
3175 
3176         exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3177                 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
3178     }
3179 
3180     @Test
testSetUserProvisioningState_unprivileged()3181     public void testSetUserProvisioningState_unprivileged() throws Exception {
3182         setupProfileOwner();
3183         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3184                 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
3185                         CALLER_USER_HANDLE));
3186     }
3187 
3188     @Test
testSetUserProvisioningState_noManagement()3189     public void testSetUserProvisioningState_noManagement() {
3190         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3191         mContext.callerPermissions.add(permission.MANAGE_USERS);
3192         assertExpectException(IllegalStateException.class,
3193                 /* messageRegex= */ "change provisioning state unless a .* owner is set",
3194                 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
3195                         CALLER_USER_HANDLE));
3196         assertThat(dpm.getUserProvisioningState())
3197                 .isEqualTo(DevicePolicyManager.STATE_USER_UNMANAGED);
3198     }
3199 
3200     @Test
testSetUserProvisioningState_deviceOwnerFromSetupWizard()3201     public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
3202         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3203         setupDeviceOwner();
3204 
3205         exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
3206                 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
3207                 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
3208     }
3209 
3210     @Test
testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()3211     public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
3212             throws Exception {
3213         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3214         setupDeviceOwner();
3215 
3216         exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
3217                 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
3218                 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
3219     }
3220 
3221     @Test
testSetUserProvisioningState_deviceOwnerWithoutSetupWizard()3222     public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
3223         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3224         setupDeviceOwner();
3225 
3226         exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
3227                 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
3228     }
3229 
3230     @Test
testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()3231     public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
3232             throws Exception {
3233         setupProfileOwner();
3234 
3235         exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3236                 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
3237                 DevicePolicyManager.STATE_USER_PROFILE_FINALIZED);
3238     }
3239 
3240     @Test
testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()3241     public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
3242             throws Exception {
3243         setupProfileOwner();
3244 
3245         exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3246                 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
3247                 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
3248     }
3249 
3250     @Test
testSetUserProvisioningState_managedProfileWithoutSetupWizard()3251     public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
3252         setupProfileOwner();
3253 
3254         exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3255                 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
3256     }
3257 
3258     @Test
testSetUserProvisioningState_illegalTransitionOutOfFinalized1()3259     public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
3260         setupProfileOwner();
3261 
3262         assertExpectException(IllegalStateException.class,
3263                 /* messageRegex= */ "Cannot move to user provisioning state",
3264                 () -> exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3265                         DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
3266                         DevicePolicyManager.STATE_USER_UNMANAGED));
3267     }
3268 
3269     @Test
testSetUserProvisioningState_profileFinalized_canTransitionToUserUnmanaged()3270     public void testSetUserProvisioningState_profileFinalized_canTransitionToUserUnmanaged()
3271             throws Exception {
3272         setupProfileOwner();
3273 
3274         exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3275                 DevicePolicyManager.STATE_USER_PROFILE_FINALIZED,
3276                 DevicePolicyManager.STATE_USER_UNMANAGED);
3277     }
3278 
3279     @Test
testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()3280     public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
3281             throws Exception {
3282         setupProfileOwner();
3283 
3284         assertExpectException(IllegalStateException.class,
3285                 /* messageRegex= */ "Cannot move to user provisioning state",
3286                 () -> exerciseUserProvisioningTransitions(CALLER_USER_HANDLE,
3287                         DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
3288                         DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
3289     }
3290 
exerciseUserProvisioningTransitions(int userId, int... states)3291     private void exerciseUserProvisioningTransitions(int userId, int... states) {
3292         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3293         mContext.callerPermissions.add(permission.MANAGE_USERS);
3294 
3295         assertThat(dpm.getUserProvisioningState())
3296                 .isEqualTo(DevicePolicyManager.STATE_USER_UNMANAGED);
3297         for (int state : states) {
3298             dpm.setUserProvisioningState(state, userId);
3299             assertThat(dpm.getUserProvisioningState()).isEqualTo(state);
3300         }
3301     }
3302 
setupProfileOwner()3303     private void setupProfileOwner() throws Exception {
3304         mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3305 
3306         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
3307         dpm.setActiveAdmin(admin1, false);
3308         assertThat(dpm.setProfileOwner(admin1, CALLER_USER_HANDLE)).isTrue();
3309 
3310         mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3311     }
3312 
setupProfileOwnerOnUser0()3313     private void setupProfileOwnerOnUser0() throws Exception {
3314         mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3315 
3316         setUpPackageManagerForAdmin(admin1, DpmMockContext.SYSTEM_UID);
3317         dpm.setActiveAdmin(admin1, false);
3318         assertThat(dpm.setProfileOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
3319 
3320         mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3321     }
3322 
setupDeviceOwner()3323     private void setupDeviceOwner() throws Exception {
3324         mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3325 
3326         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
3327         dpm.setActiveAdmin(admin1, false);
3328         assertThat(dpm.setDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
3329 
3330         mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3331     }
3332 
3333     @Test
testSetMaximumTimeToLock()3334     public void testSetMaximumTimeToLock() {
3335         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
3336 
3337         dpm.setActiveAdmin(admin1, /* replace =*/ false);
3338         dpm.setActiveAdmin(admin2, /* replace =*/ false);
3339 
3340         reset(getServices().powerManagerInternal);
3341         reset(getServices().settings);
3342 
3343         dpm.setMaximumTimeToLock(admin1, 0);
3344         verifyScreenTimeoutCall(null, CALLER_USER_HANDLE);
3345         verifyStayOnWhilePluggedCleared(false);
3346         reset(getServices().powerManagerInternal);
3347         reset(getServices().settings);
3348 
3349         dpm.setMaximumTimeToLock(admin1, 1);
3350         verifyScreenTimeoutCall(1L, CALLER_USER_HANDLE);
3351         verifyStayOnWhilePluggedCleared(true);
3352         reset(getServices().powerManagerInternal);
3353         reset(getServices().settings);
3354 
3355         dpm.setMaximumTimeToLock(admin2, 10);
3356         verifyScreenTimeoutCall(null, CALLER_USER_HANDLE);
3357         verifyStayOnWhilePluggedCleared(false);
3358         reset(getServices().powerManagerInternal);
3359         reset(getServices().settings);
3360 
3361         dpm.setMaximumTimeToLock(admin1, 5);
3362         verifyScreenTimeoutCall(5L, CALLER_USER_HANDLE);
3363         verifyStayOnWhilePluggedCleared(true);
3364         reset(getServices().powerManagerInternal);
3365         reset(getServices().settings);
3366 
3367         dpm.setMaximumTimeToLock(admin2, 4);
3368         verifyScreenTimeoutCall(4L, CALLER_USER_HANDLE);
3369         verifyStayOnWhilePluggedCleared(true);
3370         reset(getServices().powerManagerInternal);
3371         reset(getServices().settings);
3372 
3373         dpm.setMaximumTimeToLock(admin1, 0);
3374         reset(getServices().powerManagerInternal);
3375         reset(getServices().settings);
3376 
3377         dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
3378         verifyScreenTimeoutCall(Long.MAX_VALUE, CALLER_USER_HANDLE);
3379         verifyStayOnWhilePluggedCleared(true);
3380         reset(getServices().powerManagerInternal);
3381         reset(getServices().settings);
3382 
3383         dpm.setMaximumTimeToLock(admin2, 10);
3384         verifyScreenTimeoutCall(10L, CALLER_USER_HANDLE);
3385         verifyStayOnWhilePluggedCleared(true);
3386         reset(getServices().powerManagerInternal);
3387         reset(getServices().settings);
3388 
3389         // There's no restriction; should be set to MAX.
3390         dpm.setMaximumTimeToLock(admin2, 0);
3391         verifyScreenTimeoutCall(Long.MAX_VALUE, CALLER_USER_HANDLE);
3392         verifyStayOnWhilePluggedCleared(false);
3393     }
3394 
3395     @Test
testSupervisionConfig()3396     public void testSupervisionConfig() throws Exception {
3397         final int uid = UserHandle.getUid(15, 19436);
3398         addManagedProfile(admin1, uid, admin1);
3399         mContext.binder.callingUid = uid;
3400 
3401         verifySupervisionConfig(uid, null, null);
3402         verifySupervisionConfig(uid, "", null);
3403         verifySupervisionConfig(uid, null, "");
3404         verifySupervisionConfig(uid, "", "");
3405 
3406         verifySupervisionConfig(uid, admin1.flattenToString(), null);
3407         verifySupervisionConfig(uid, admin1.flattenToString(), "");
3408 
3409         verifySupervisionConfig(uid, null, admin1.getPackageName());
3410         verifySupervisionConfig(uid, "", admin1.getPackageName());
3411     }
3412 
verifySupervisionConfig( int uid , String configComponentName, String configPackageName)3413     private void verifySupervisionConfig(
3414             int uid , String configComponentName, String configPackageName) {
3415         final boolean isAdmin = admin1.flattenToString().equals(configComponentName)
3416                 || admin1.getPackageName().equals(configPackageName);
3417 
3418         final UserHandle user = UserHandle.getUserHandleForUid(uid);
3419         final DevicePolicyManagerInternal dpmi =
3420                 LocalServices.getService(DevicePolicyManagerInternal.class);
3421 
3422         when(mServiceContext.resources
3423                 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
3424                 .thenReturn(configComponentName);
3425 
3426         when(mServiceContext.resources
3427                 .getString(R.string.config_systemSupervision))
3428                 .thenReturn(configPackageName);
3429 
3430         if (isAdmin) {
3431             assertThat(dpmi.isActiveSupervisionApp(uid)).isTrue();
3432             assertThat(dpm.getProfileOwnerOrDeviceOwnerSupervisionComponent(user))
3433                         .isEqualTo(admin1);
3434             assertThat(dpm.isSupervisionComponent(admin1)).isTrue();
3435         } else {
3436             assertThat(dpmi.isActiveSupervisionApp(uid)).isFalse();
3437             assertThat(dpm.getProfileOwnerOrDeviceOwnerSupervisionComponent(user)).isNull();
3438             assertThat(dpm.isSupervisionComponent(admin1)).isFalse();
3439         }
3440     }
3441 
3442     // Test if lock timeout on managed profile is handled correctly depending on whether profile
3443     // uses separate challenge.
3444     @Test
testSetMaximumTimeToLockProfile()3445     public void testSetMaximumTimeToLockProfile() throws Exception {
3446         final int PROFILE_USER = 15;
3447         final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
3448         addManagedProfile(admin1, PROFILE_ADMIN, admin1);
3449         mContext.binder.callingUid = PROFILE_ADMIN;
3450         final DevicePolicyManagerInternal dpmi =
3451                 LocalServices.getService(DevicePolicyManagerInternal.class);
3452 
3453         dpm.setMaximumTimeToLock(admin1, 0);
3454 
3455         reset(getServices().powerManagerInternal);
3456         reset(getServices().settings);
3457 
3458         // First add timeout for the profile.
3459         dpm.setMaximumTimeToLock(admin1, 10);
3460         verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
3461 
3462         reset(getServices().powerManagerInternal);
3463         reset(getServices().settings);
3464 
3465         // Add separate challenge
3466         when(getServices().lockPatternUtils
3467                 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
3468         dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
3469 
3470         verifyScreenTimeoutCall(10L, PROFILE_USER);
3471         verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
3472 
3473         reset(getServices().powerManagerInternal);
3474         reset(getServices().settings);
3475 
3476         // Remove the timeout.
3477         dpm.setMaximumTimeToLock(admin1, 0);
3478         verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
3479         verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
3480 
3481         reset(getServices().powerManagerInternal);
3482         reset(getServices().settings);
3483 
3484         // Add it back.
3485         dpm.setMaximumTimeToLock(admin1, 10);
3486         verifyScreenTimeoutCall(10L, PROFILE_USER);
3487         verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
3488 
3489         reset(getServices().powerManagerInternal);
3490         reset(getServices().settings);
3491 
3492         // Remove separate challenge.
3493         reset(getServices().lockPatternUtils);
3494         when(getServices().lockPatternUtils
3495                 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
3496         dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
3497         when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
3498 
3499         verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
3500         verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
3501 
3502         reset(getServices().powerManagerInternal);
3503         reset(getServices().settings);
3504 
3505         // Remove the timeout.
3506         dpm.setMaximumTimeToLock(admin1, 0);
3507         verifyScreenTimeoutCall(null, PROFILE_USER);
3508         verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
3509     }
3510 
3511     @Test
testSetRequiredStrongAuthTimeout_DeviceOwner()3512     public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
3513         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3514         setupDeviceOwner();
3515         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3516 
3517         final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
3518         final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
3519         final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
3520         final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
3521                 - ONE_MINUTE;
3522 
3523         // verify that the minimum timeout cannot be modified on user builds (system property is
3524         // not being read)
3525         getServices().buildMock.isDebuggable = false;
3526 
3527         dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
3528         assertThat(MAX_MINUS_ONE_MINUTE).isEqualTo(dpm.getRequiredStrongAuthTimeout(admin1));
3529         assertThat(MAX_MINUS_ONE_MINUTE).isEqualTo(dpm.getRequiredStrongAuthTimeout(null));
3530 
3531         verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
3532 
3533         // restore to the debuggable build state
3534         getServices().buildMock.isDebuggable = true;
3535 
3536         // reset to default (0 means the admin is not participating, so default should be returned)
3537         dpm.setRequiredStrongAuthTimeout(admin1, 0);
3538 
3539         // aggregation should be the default if unset by any admin
3540         assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS)
3541                 .isEqualTo(dpm.getRequiredStrongAuthTimeout(null));
3542 
3543         // admin not participating by default
3544         assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(0);
3545 
3546         //clamping from the top
3547         dpm.setRequiredStrongAuthTimeout(admin1,
3548                 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
3549         assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS)
3550                 .isEqualTo(dpm.getRequiredStrongAuthTimeout(admin1));
3551         assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS)
3552                 .isEqualTo(dpm.getRequiredStrongAuthTimeout(null));
3553 
3554         // 0 means the admin is not participating, so default should be returned
3555         dpm.setRequiredStrongAuthTimeout(admin1, 0);
3556         assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(0);
3557         assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS)
3558                 .isEqualTo(dpm.getRequiredStrongAuthTimeout(null));
3559 
3560         // clamping from the bottom
3561         dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
3562         assertThat(dpm.getRequiredStrongAuthTimeout(admin1))
3563                 .isEqualTo(MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3564         assertThat(dpm.getRequiredStrongAuthTimeout(null))
3565                 .isEqualTo(MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3566 
3567         // values within range
3568         dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
3569         assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(MIN_PLUS_ONE_MINUTE);
3570         assertThat(dpm.getRequiredStrongAuthTimeout(null)).isEqualTo(MIN_PLUS_ONE_MINUTE);
3571 
3572         dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
3573         assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(MAX_MINUS_ONE_MINUTE);
3574         assertThat(dpm.getRequiredStrongAuthTimeout(null)).isEqualTo(MAX_MINUS_ONE_MINUTE);
3575 
3576         // reset to default
3577         dpm.setRequiredStrongAuthTimeout(admin1, 0);
3578         assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(0);
3579         assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS)
3580                 .isEqualTo(dpm.getRequiredStrongAuthTimeout(null));
3581 
3582         // negative value
3583         assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3584                 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
3585     }
3586 
verifyScreenTimeoutCall(Long expectedTimeout, int userId)3587     private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
3588         if (expectedTimeout == null) {
3589             verify(getServices().powerManagerInternal, times(0))
3590                     .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
3591         } else {
3592             verify(getServices().powerManagerInternal, times(1))
3593                     .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
3594         }
3595     }
3596 
verifyStayOnWhilePluggedCleared(boolean cleared)3597     private void verifyStayOnWhilePluggedCleared(boolean cleared) {
3598         // TODO Verify calls to settingsGlobalPutInt.  Tried but somehow mockito threw
3599         // UnfinishedVerificationException.
3600     }
3601 
setup_DeviceAdminFeatureOff()3602     private void setup_DeviceAdminFeatureOff() throws Exception {
3603         when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
3604                 .thenReturn(false);
3605         when(getServices().ipackageManager
3606                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(false);
3607         initializeDpms();
3608         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(true);
3609         when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
3610                 .thenReturn(true);
3611         setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3612 
3613         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3614     }
3615 
3616     @Test
testIsProvisioningAllowed_DeviceAdminFeatureOff()3617     public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
3618         setup_DeviceAdminFeatureOff();
3619         mContext.packageName = admin1.getPackageName();
3620         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3621         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
3622         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
3623         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3624 
3625         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(true);
3626         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
3627     }
3628 
3629     @Test
testCheckProvisioningPreCondition_DeviceAdminFeatureOff()3630     public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
3631         setup_DeviceAdminFeatureOff();
3632         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3633         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3634                 DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED);
3635         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3636                 DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED);
3637         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3638                 DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED);
3639     }
3640 
setup_ManagedProfileFeatureOff()3641     private void setup_ManagedProfileFeatureOff() throws Exception {
3642         when(getServices().ipackageManager
3643                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(false);
3644         initializeDpms();
3645         when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
3646                 .thenReturn(true);
3647         setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3648 
3649         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3650     }
3651 
3652     @Test
testIsProvisioningAllowed_ManagedProfileFeatureOff()3653     public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
3654         setup_ManagedProfileFeatureOff();
3655         mContext.packageName = admin1.getPackageName();
3656         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3657         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3658         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
3659         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3660 
3661         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(true);
3662         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3663     }
3664 
3665     @Test
testCheckProvisioningPreCondition_ManagedProfileFeatureOff()3666     public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
3667         setup_ManagedProfileFeatureOff();
3668         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3669         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3670                 DevicePolicyManager.STATUS_OK);
3671         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3672                 DevicePolicyManager.STATUS_OK);
3673         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3674                 DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED);
3675     }
3676 
setup_firstBoot_systemUser()3677     private void setup_firstBoot_systemUser() throws Exception {
3678         when(getServices().ipackageManager
3679                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true);
3680         when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, false))
3681                 .thenReturn(true);
3682         setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3683         when(getServices().userManager.getProfileParent(UserHandle.USER_SYSTEM)).thenReturn(null);
3684 
3685         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3686     }
3687 
3688     /* Tests provisions from system user during first boot. */
3689     @Test
testIsProvisioningAllowed_firstBoot_systemUser()3690     public void testIsProvisioningAllowed_firstBoot_systemUser() throws Exception {
3691         setup_firstBoot_systemUser();
3692         mContext.packageName = admin1.getPackageName();
3693         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3694 
3695         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(false);
3696         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3697         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
3698         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3699 
3700         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(true);
3701         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3702     }
3703 
3704     @Test
testCheckProvisioningPreCondition_firstBoot_systemUser()3705     public void testCheckProvisioningPreCondition_firstBoot_systemUser()
3706             throws Exception {
3707         setup_firstBoot_systemUser();
3708         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3709 
3710         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(false);
3711         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3712                 DevicePolicyManager.STATUS_OK);
3713         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3714                 DevicePolicyManager.STATUS_OK);
3715         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3716                 DevicePolicyManager.STATUS_OK);
3717 
3718         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(true);
3719         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3720                 DevicePolicyManager.STATUS_OK);
3721     }
3722 
setup_systemUserSetupComplete_systemUser()3723     private void setup_systemUserSetupComplete_systemUser() throws Exception {
3724         when(getServices().ipackageManager
3725                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true);
3726         when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, false))
3727                 .thenReturn(true);
3728         setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3729         when(getServices().userManager.getProfileParent(UserHandle.USER_SYSTEM)).thenReturn(null);
3730 
3731         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3732     }
3733 
setup_withDo_systemUser()3734     private void setup_withDo_systemUser() throws Exception {
3735         setDeviceOwner();
3736         setup_systemUserSetupComplete_systemUser();
3737         setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3738     }
3739 
setup_withDo_systemUser_ManagedProfile()3740     private void setup_withDo_systemUser_ManagedProfile() throws Exception {
3741         setup_withDo_systemUser();
3742         final int MANAGED_PROFILE_USER_ID = 18;
3743         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
3744         when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
3745                 false /* we can't remove a managed profile */)).thenReturn(false);
3746     }
3747 
3748     @Test
testIsProvisioningAllowed_systemUserSetupComplete_systemUser()3749     public void testIsProvisioningAllowed_systemUserSetupComplete_systemUser()
3750             throws Exception {
3751         setup_systemUserSetupComplete_systemUser();
3752         mContext.packageName = admin1.getPackageName();
3753         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3754         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3755                 false/* because of completed device setup */);
3756         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3757                 false/* because of completed device setup */);
3758         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3759     }
3760 
3761     @Test
testCheckProvisioningPreCondition_systemUserSetupComplete_systemUser()3762     public void testCheckProvisioningPreCondition_systemUserSetupComplete_systemUser()
3763             throws Exception {
3764         setup_systemUserSetupComplete_systemUser();
3765         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3766         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3767                 DevicePolicyManager.STATUS_USER_SETUP_COMPLETED);
3768         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3769                 DevicePolicyManager.STATUS_USER_SETUP_COMPLETED);
3770         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3771                 DevicePolicyManager.STATUS_OK);
3772     }
3773 
3774     @Test
testProvisioning_withDo_systemUser()3775     public void testProvisioning_withDo_systemUser() throws Exception {
3776         setup_withDo_systemUser();
3777         mContext.packageName = admin1.getPackageName();
3778         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3779 
3780         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3781                 DevicePolicyManager.STATUS_HAS_DEVICE_OWNER);
3782         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3783                 DevicePolicyManager.STATUS_HAS_DEVICE_OWNER);
3784         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
3785         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
3786 
3787         // COMP mode NOT is allowed.
3788         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3789                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3790         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3791 
3792         // And other DPCs can NOT provision a managed profile.
3793         assertCheckProvisioningPreCondition(
3794                 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3795                 DpmMockContext.ANOTHER_PACKAGE_NAME,
3796                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3797         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3798                 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3799     }
3800 
3801     @Test
testProvisioning_withDo_systemUser_restrictedBySystem()3802     public void testProvisioning_withDo_systemUser_restrictedBySystem()
3803             throws Exception {
3804         setup_withDo_systemUser();
3805         mContext.packageName = admin1.getPackageName();
3806         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3807         // The DO should not be allowed to initiate provisioning if the restriction is set by
3808         // another entity.
3809         when(getServices().userManager.hasUserRestriction(
3810                 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3811                 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3812                 .thenReturn(true);
3813         when(getServices().userManager.getUserRestrictionSource(
3814                 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3815                 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3816                 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3817         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3818                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3819         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3820 
3821         assertCheckProvisioningPreCondition(
3822                 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3823                 DpmMockContext.ANOTHER_PACKAGE_NAME,
3824                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3825         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3826                 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3827     }
3828 
3829     @Test
testCheckCannotSetProfileOwnerWithDeviceOwner()3830     public void testCheckCannotSetProfileOwnerWithDeviceOwner() throws Exception {
3831         setup_withDo_systemUser();
3832         final int managedProfileUserId = 18;
3833         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 1308);
3834 
3835         final int userId = UserHandle.getUserId(managedProfileAdminUid);
3836         getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
3837                 UserHandle.USER_SYSTEM);
3838         mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3839         setUpPackageManagerForFakeAdmin(admin1, managedProfileAdminUid, admin1);
3840         dpm.setActiveAdmin(admin1, false, userId);
3841         assertThat(dpm.setProfileOwner(admin1, userId)).isFalse();
3842         mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3843     }
3844 
3845     @Test
testCheckProvisioningPreCondition_attemptingComp()3846     public void testCheckProvisioningPreCondition_attemptingComp() throws Exception {
3847         setup_withDo_systemUser_ManagedProfile();
3848         mContext.packageName = admin1.getPackageName();
3849         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3850 
3851         // We can delete the managed profile to create a new one, so provisioning is allowed.
3852         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3853                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3854         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3855         assertCheckProvisioningPreCondition(
3856                 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3857                 DpmMockContext.ANOTHER_PACKAGE_NAME,
3858                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3859         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3860                 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3861     }
3862 
3863     @Test
testCheckProvisioningPreCondition_comp_cannot_remove_profile()3864     public void testCheckProvisioningPreCondition_comp_cannot_remove_profile()
3865             throws Exception {
3866         setup_withDo_systemUser_ManagedProfile();
3867         mContext.packageName = admin1.getPackageName();
3868         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3869         when(getServices().userManager.hasUserRestriction(
3870                 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3871                 eq(UserHandle.SYSTEM)))
3872                 .thenReturn(true);
3873         when(getServices().userManager.getUserRestrictionSource(
3874                 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3875                 eq(UserHandle.SYSTEM)))
3876                 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3877 
3878         // We can't remove the profile to create a new one.
3879         assertCheckProvisioningPreCondition(
3880                 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3881                 DpmMockContext.ANOTHER_PACKAGE_NAME,
3882                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3883         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3884                 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3885 
3886         // But the device owner can still do it because it has set the restriction itself.
3887         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3888                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3889         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3890     }
3891 
3892     // TODO(b/174859111): move to automotive-only section
setup_firstBoot_headlessSystemUserMode()3893     private void setup_firstBoot_headlessSystemUserMode() throws Exception {
3894         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3895         when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, false))
3896                 .thenReturn(true);
3897         setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3898         when(getServices().userManager.getProfileParent(UserHandle.USER_SYSTEM)).thenReturn(null);
3899     }
3900 
3901     /**
3902      * TODO(b/174859111): move to automotive-only section
3903      * Tests provision from secondary user during first boot.
3904     **/
3905     @Test
testIsProvisioningAllowed_firstBoot_secondaryUser()3906     public void testIsProvisioningAllowed_firstBoot_secondaryUser() throws Exception {
3907         setup_firstBoot_headlessSystemUserMode();
3908         mContext.packageName = admin1.getPackageName();
3909         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3910         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
3911         // Provisioning device from secondary user should fail in non-headless system user mode.
3912         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(false);
3913         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
3914         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
3915 
3916         // Required for ACTION_PROVISION_MANAGED_PROFILE if allowed to add managed profile from
3917         // secondary user
3918         when(getServices().userManager.canAddMoreManagedProfiles(CALLER_USER_HANDLE, false))
3919                 .thenReturn(true);
3920         when(getServices().ipackageManager
3921                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true);
3922         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3923 
3924         // Provisioning device from secondary user should be allowed in headless system user mode.
3925         when(getServices().userManagerForMock.isHeadlessSystemUserMode()).thenReturn(true);
3926         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3927     }
3928 
setup_provisionManagedProfileWithDeviceOwner_primaryUser()3929     private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
3930         setDeviceOwner();
3931 
3932         when(getServices().ipackageManager
3933                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true);
3934         when(getServices().userManager.getProfileParent(CALLER_USER_HANDLE))
3935             .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3936         when(getServices().userManager.canAddMoreManagedProfiles(CALLER_USER_HANDLE,
3937                 false)).thenReturn(true);
3938         setUserSetupCompleteForUser(false, CALLER_USER_HANDLE);
3939 
3940         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
3941     }
3942 
3943     @Test
testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()3944     public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3945             throws Exception {
3946         setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3947         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3948         mContext.packageName = admin1.getPackageName();
3949         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3950     }
3951 
3952     @Test
testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()3953     public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
3954             throws Exception {
3955         setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3956         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3957 
3958         // COMP mode is NOT allowed.
3959         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3960                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3961     }
3962 
setup_provisionManagedProfileOneAlreadyExist_primaryUser()3963     private void setup_provisionManagedProfileOneAlreadyExist_primaryUser() throws Exception {
3964         setDeviceOwner();
3965 
3966         when(getServices().ipackageManager
3967                 .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true);
3968         when(getServices().userManager.hasUserRestriction(
3969                 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3970                 eq(UserHandle.of(CALLER_USER_HANDLE))))
3971                 .thenReturn(true);
3972         when(getServices().userManager.canAddMoreManagedProfiles(CALLER_USER_HANDLE,
3973                 false /* we can't remove a managed profile */)).thenReturn(false);
3974         setUserSetupCompleteForUser(false, CALLER_USER_HANDLE);
3975 
3976         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3977     }
3978 
3979     @Test
testIsProvisioningAllowed_provisionManagedProfile_oneAlreadyExists_primaryUser()3980     public void testIsProvisioningAllowed_provisionManagedProfile_oneAlreadyExists_primaryUser()
3981             throws Exception {
3982         setup_provisionManagedProfileOneAlreadyExist_primaryUser();
3983         mContext.packageName = admin1.getPackageName();
3984         setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3985         assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3986     }
3987 
3988     @Test
testCheckProvisioningPreCondition_provisionManagedProfile_oneAlreadyExists_primaryUser()3989     public void testCheckProvisioningPreCondition_provisionManagedProfile_oneAlreadyExists_primaryUser()
3990             throws Exception {
3991         setup_provisionManagedProfileOneAlreadyExist_primaryUser();
3992         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3993         assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3994                 DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE);
3995     }
3996 
3997     @Test
testCheckProvisioningPreCondition_permission()3998     public void testCheckProvisioningPreCondition_permission() {
3999         // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
4000         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4001                 () -> dpm.checkProvisioningPrecondition(
4002                         DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
4003     }
4004 
4005     @Test
testForceUpdateUserSetupComplete_permission()4006     public void testForceUpdateUserSetupComplete_permission() {
4007         // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
4008         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4009                 () -> dpm.forceUpdateUserSetupComplete(UserHandle.USER_SYSTEM));
4010     }
4011 
4012     @Test
testForceUpdateUserSetupComplete_forcesUpdate()4013     public void testForceUpdateUserSetupComplete_forcesUpdate() {
4014         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
4015         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4016         final int userId = UserHandle.getUserId(mContext.binder.callingUid);
4017 
4018         // GIVEN userComplete is false in SettingsProvider
4019         setUserSetupCompleteForUser(false, userId);
4020 
4021         // GIVEN userComplete is true in DPM
4022         DevicePolicyData userData = new DevicePolicyData(userId);
4023         userData.mUserSetupComplete = true;
4024         dpms.mUserData.put(userId, userData);
4025 
4026         assertThat(dpms.hasUserSetupCompleted()).isTrue();
4027 
4028         dpm.forceUpdateUserSetupComplete(userId);
4029 
4030         // THEN the state in dpms is changed
4031         assertThat(dpms.hasUserSetupCompleted()).isFalse();
4032     }
4033 
clearDeviceOwner()4034     private void clearDeviceOwner() {
4035         getServices().addTestPackageUid(admin1.getPackageName(),
4036                 DpmMockContext.CALLER_SYSTEM_USER_UID);
4037 
4038         mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4039         runAsCaller(mAdmin1Context, dpms, dpm -> {
4040             dpm.clearDeviceOwnerApp(admin1.getPackageName());
4041         });
4042     }
4043 
4044     @Test
testGetLastSecurityLogRetrievalTime()4045     public void testGetLastSecurityLogRetrievalTime() throws Exception {
4046         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4047         setupDeviceOwner();
4048 
4049         // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4050         // feature is disabled because there are non-affiliated secondary users.
4051         getServices().removeUser(CALLER_USER_HANDLE);
4052         when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
4053                 .thenReturn(true);
4054 
4055         // No logs were retrieved so far.
4056         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(-1);
4057 
4058         // Enabling logging should not change the timestamp.
4059         dpm.setSecurityLoggingEnabled(admin1, true);
4060         verify(getServices().settings).securityLogSetLoggingEnabledProperty(true);
4061 
4062         when(getServices().settings.securityLogGetLoggingEnabledProperty()).thenReturn(true);
4063         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(-1);
4064 
4065         // Retrieving the logs should update the timestamp.
4066         final long beforeRetrieval = System.currentTimeMillis();
4067         dpm.retrieveSecurityLogs(admin1);
4068         final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
4069         final long afterRetrieval = System.currentTimeMillis();
4070         assertThat(firstSecurityLogRetrievalTime >= beforeRetrieval).isTrue();
4071         assertThat(firstSecurityLogRetrievalTime <= afterRetrieval).isTrue();
4072 
4073         // Retrieving the pre-boot logs should update the timestamp.
4074         Thread.sleep(2);
4075         dpm.retrievePreRebootSecurityLogs(admin1);
4076         final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
4077         assertThat(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime).isTrue();
4078 
4079         // Checking the timestamp again should not change it.
4080         Thread.sleep(2);
4081         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(secondSecurityLogRetrievalTime);
4082 
4083         // Retrieving the logs again should update the timestamp.
4084         dpm.retrieveSecurityLogs(admin1);
4085         final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
4086         assertThat(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime).isTrue();
4087 
4088         // Disabling logging should not change the timestamp.
4089         Thread.sleep(2);
4090         dpm.setSecurityLoggingEnabled(admin1, false);
4091         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime);
4092 
4093         // Restarting the DPMS should not lose the timestamp.
4094         initializeDpms();
4095         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime);
4096 
4097         // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4098         mContext.binder.callingUid = 1234567;
4099         mContext.callerPermissions.add(permission.MANAGE_USERS);
4100         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime);
4101         mContext.callerPermissions.remove(permission.MANAGE_USERS);
4102 
4103         // System can retrieve the timestamp.
4104         mContext.binder.clearCallingIdentity();
4105         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime);
4106 
4107         // Removing the device owner should clear the timestamp.
4108         clearDeviceOwner();
4109         assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(-1);
4110     }
4111 
4112     @Test
testSetConfiguredNetworksLockdownStateWithDO()4113     public void testSetConfiguredNetworksLockdownStateWithDO() throws Exception {
4114         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4115         setupDeviceOwner();
4116         dpm.setConfiguredNetworksLockdownState(admin1, true);
4117         verify(getServices().settings).settingsGlobalPutInt(
4118                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
4119 
4120         dpm.setConfiguredNetworksLockdownState(admin1, false);
4121         verify(getServices().settings).settingsGlobalPutInt(
4122                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
4123     }
4124 
4125     @Test
testSetConfiguredNetworksLockdownStateWithPO()4126     public void testSetConfiguredNetworksLockdownStateWithPO() throws Exception {
4127         setupProfileOwner();
4128         assertExpectException(SecurityException.class, null,
4129                 () -> dpm.setConfiguredNetworksLockdownState(admin1, false));
4130         verify(getServices().settings, never()).settingsGlobalPutInt(
4131                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
4132     }
4133 
4134     @Test
testSetConfiguredNetworksLockdownStateWithPOOfOrganizationOwnedDevice()4135     public void testSetConfiguredNetworksLockdownStateWithPOOfOrganizationOwnedDevice()
4136             throws Exception {
4137         setupProfileOwner();
4138         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4139         dpm.setConfiguredNetworksLockdownState(admin1, true);
4140         verify(getServices().settings).settingsGlobalPutInt(
4141                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
4142 
4143         dpm.setConfiguredNetworksLockdownState(admin1, false);
4144         verify(getServices().settings).settingsGlobalPutInt(
4145                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
4146     }
4147 
4148     @Test
testUpdateNetworkPreferenceOnStartUser()4149     public void testUpdateNetworkPreferenceOnStartUser() throws Exception {
4150         final int managedProfileUserId = 15;
4151         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4152         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4153         mContext.binder.callingUid = managedProfileAdminUid;
4154         mServiceContext.permissions.add(permission.INTERACT_ACROSS_USERS_FULL);
4155 
4156         dpms.handleStartUser(managedProfileUserId);
4157         ProfileNetworkPreference preferenceDetails =
4158                 new ProfileNetworkPreference.Builder()
4159                 .setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT)
4160                 .build();
4161         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4162         preferences.add(preferenceDetails);
4163         verify(getServices().connectivityManager, times(1))
4164                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4165                 null, null);
4166     }
4167 
4168     @Test
testUpdateNetworkPreferenceOnStopUser()4169     public void testUpdateNetworkPreferenceOnStopUser() throws Exception {
4170         final int managedProfileUserId = 15;
4171         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4172         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4173         mContext.binder.callingUid = managedProfileAdminUid;
4174         mServiceContext.permissions.add(permission.INTERACT_ACROSS_USERS_FULL);
4175 
4176         dpms.handleStopUser(managedProfileUserId);
4177         ProfileNetworkPreference preferenceDetails =
4178                 new ProfileNetworkPreference.Builder()
4179                         .setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT)
4180                         .build();
4181         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4182         preferences.add(preferenceDetails);
4183         verify(getServices().connectivityManager, times(1))
4184                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4185                         null, null);
4186     }
4187 
4188     @Test
testGetSetPreferentialNetworkService()4189     public void testGetSetPreferentialNetworkService() throws Exception {
4190         assertExpectException(SecurityException.class, null,
4191                 () -> dpm.setPreferentialNetworkServiceEnabled(false));
4192 
4193         assertExpectException(SecurityException.class, null,
4194                 () -> dpm.isPreferentialNetworkServiceEnabled());
4195 
4196         final int managedProfileUserId = 15;
4197         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4198         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4199         mContext.binder.callingUid = managedProfileAdminUid;
4200 
4201         dpm.setPreferentialNetworkServiceEnabled(false);
4202         assertThat(dpm.isPreferentialNetworkServiceEnabled()).isFalse();
4203 
4204         ProfileNetworkPreference preferenceDetails =
4205                 new ProfileNetworkPreference.Builder()
4206                         .setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT)
4207                         .build();
4208         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4209         preferences.add(preferenceDetails);
4210         verify(getServices().connectivityManager, times(1))
4211                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4212                         null, null);
4213 
4214         dpm.setPreferentialNetworkServiceEnabled(true);
4215         assertThat(dpm.isPreferentialNetworkServiceEnabled()).isTrue();
4216 
4217         ProfileNetworkPreference preferenceDetails2 =
4218                 new ProfileNetworkPreference.Builder()
4219                         .setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE)
4220                         .setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1)
4221                         .build();
4222         List<ProfileNetworkPreference> preferences2 = new ArrayList<>();
4223         preferences2.add(preferenceDetails);
4224         verify(getServices().connectivityManager, times(1))
4225                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences2,
4226                         null, null);
4227     }
4228 
4229     @Test
testSetPreferentialNetworkServiceConfig_noProfileOwner()4230     public void testSetPreferentialNetworkServiceConfig_noProfileOwner() throws Exception {
4231         assertExpectException(SecurityException.class, null,
4232                 () -> dpm.setPreferentialNetworkServiceConfigs(
4233                         List.of(PreferentialNetworkServiceConfig.DEFAULT)));
4234     }
4235 
4236     @Test
testIsPreferentialNetworkServiceEnabled_noProfileOwner()4237     public void testIsPreferentialNetworkServiceEnabled_noProfileOwner() throws Exception {
4238         assertExpectException(SecurityException.class, null,
4239                 () -> dpm.isPreferentialNetworkServiceEnabled());
4240     }
4241 
4242     @Test
testSetPreferentialNetworkServiceConfig_invalidConfig()4243     public void testSetPreferentialNetworkServiceConfig_invalidConfig() throws Exception {
4244         final int managedProfileUserId = 15;
4245         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4246         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4247         mContext.binder.callingUid = managedProfileAdminUid;
4248 
4249         PreferentialNetworkServiceConfig.Builder preferentialNetworkServiceConfigBuilder =
4250                 new PreferentialNetworkServiceConfig.Builder();
4251         assertExpectException(NullPointerException.class, null,
4252                 () -> preferentialNetworkServiceConfigBuilder.setIncludedUids(null));
4253         assertExpectException(NullPointerException.class, null,
4254                 () -> preferentialNetworkServiceConfigBuilder.setExcludedUids(null));
4255         assertExpectException(IllegalArgumentException.class, null,
4256                 () -> preferentialNetworkServiceConfigBuilder.setNetworkId(6));
4257         int[] includedUids = new int[]{1, 2};
4258         int[] excludedUids = new int[]{3, 4};
4259         preferentialNetworkServiceConfigBuilder.setIncludedUids(includedUids);
4260         preferentialNetworkServiceConfigBuilder.setExcludedUids(excludedUids);
4261 
4262         assertExpectException(IllegalStateException.class, null,
4263                 () -> preferentialNetworkServiceConfigBuilder.build());
4264     }
4265 
4266     @Test
testSetPreferentialNetworkServiceConfig_defaultPreference()4267     public void testSetPreferentialNetworkServiceConfig_defaultPreference() throws Exception {
4268         final int managedProfileUserId = 15;
4269         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4270         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4271         mContext.binder.callingUid = managedProfileAdminUid;
4272 
4273         dpm.setPreferentialNetworkServiceConfigs(
4274                 List.of(PreferentialNetworkServiceConfig.DEFAULT));
4275         assertThat(dpm.isPreferentialNetworkServiceEnabled()).isFalse();
4276         assertThat(dpm.getPreferentialNetworkServiceConfigs().get(0).isEnabled()).isFalse();
4277 
4278         ProfileNetworkPreference preferenceDetails =
4279                 new ProfileNetworkPreference.Builder()
4280                         .setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT)
4281                         .build();
4282         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4283         preferences.add(preferenceDetails);
4284         verify(getServices().connectivityManager, times(1))
4285                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4286                         null, null);
4287     }
4288 
4289     @Test
testSetPreferentialNetworkServiceConfig_enterprisePreference()4290     public void testSetPreferentialNetworkServiceConfig_enterprisePreference() throws Exception {
4291         PreferentialNetworkServiceConfig preferentialNetworkServiceConfigEnabled =
4292                 (new PreferentialNetworkServiceConfig.Builder())
4293                         .setEnabled(true)
4294                         .setNetworkId(NET_ENTERPRISE_ID_1)
4295                         .build();
4296 
4297         final int managedProfileUserId = 15;
4298         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4299         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4300         mContext.binder.callingUid = managedProfileAdminUid;
4301 
4302         dpm.setPreferentialNetworkServiceConfigs(List.of(preferentialNetworkServiceConfigEnabled));
4303         assertThat(dpm.getPreferentialNetworkServiceConfigs().get(0)
4304                 .isEnabled()).isTrue();
4305         ProfileNetworkPreference preferenceDetails =
4306                 new ProfileNetworkPreference.Builder()
4307                         .setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE)
4308                         .setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1)
4309                         .build();
4310         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4311         preferences.add(preferenceDetails);
4312         verify(getServices().connectivityManager, times(1))
4313                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4314                         null, null);
4315     }
4316 
4317     @Test
testSetPreferentialNetworkServiceConfig_enterprisePreferenceIncludedUids()4318     public void testSetPreferentialNetworkServiceConfig_enterprisePreferenceIncludedUids()
4319             throws Exception {
4320         final int managedProfileUserId = 15;
4321         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4322         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4323         mContext.binder.callingUid = managedProfileAdminUid;
4324 
4325         PreferentialNetworkServiceConfig preferentialNetworkServiceConfigEnabled =
4326                 (new PreferentialNetworkServiceConfig.Builder())
4327                         .setEnabled(true)
4328                         .setNetworkId(NET_ENTERPRISE_ID_1)
4329                         .setFallbackToDefaultConnectionAllowed(false)
4330                         .setIncludedUids(new int[]{1, 2})
4331                         .build();
4332         dpm.setPreferentialNetworkServiceConfigs(List.of(preferentialNetworkServiceConfigEnabled));
4333         assertThat(dpm.getPreferentialNetworkServiceConfigs().get(0)
4334                 .isEnabled()).isTrue();
4335         ProfileNetworkPreference preferenceDetails =
4336                 new ProfileNetworkPreference.Builder()
4337                         .setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK)
4338                         .setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1)
4339                         .setIncludedUids(new int[]{1, 2})
4340                         .build();
4341         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4342         preferences.add(preferenceDetails);
4343         verify(getServices().connectivityManager, times(1))
4344                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4345                         null, null);
4346     }
4347 
4348     @Test
testSetPreferentialNetworkServiceConfig_enterprisePreferenceExcludedUids()4349     public void testSetPreferentialNetworkServiceConfig_enterprisePreferenceExcludedUids()
4350             throws Exception {
4351         final int managedProfileUserId = 15;
4352         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
4353         addManagedProfile(admin1, managedProfileAdminUid, admin1);
4354         mContext.binder.callingUid = managedProfileAdminUid;
4355 
4356         PreferentialNetworkServiceConfig preferentialNetworkServiceConfigEnabled =
4357                 (new PreferentialNetworkServiceConfig.Builder())
4358                         .setEnabled(true)
4359                         .setNetworkId(NET_ENTERPRISE_ID_1)
4360                         .setFallbackToDefaultConnectionAllowed(false)
4361                         .setExcludedUids(new int[]{1, 2})
4362                         .build();
4363 
4364         dpm.setPreferentialNetworkServiceConfigs(List.of(preferentialNetworkServiceConfigEnabled));
4365         assertThat(dpm.getPreferentialNetworkServiceConfigs().get(0)
4366                 .isEnabled()).isTrue();
4367         ProfileNetworkPreference preferenceDetails =
4368                 new ProfileNetworkPreference.Builder()
4369                         .setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK)
4370                         .setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1)
4371                         .setExcludedUids(new int[]{1, 2})
4372                         .build();
4373         List<ProfileNetworkPreference> preferences = new ArrayList<>();
4374         preferences.clear();
4375         preferences.add(preferenceDetails);
4376         verify(getServices().connectivityManager, times(1))
4377                 .setProfileNetworkPreferences(UserHandle.of(managedProfileUserId), preferences,
4378                         null, null);
4379     }
4380 
4381     @Test
testSetSystemSettingFailWithNonWhitelistedSettings()4382     public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
4383         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4384         setupDeviceOwner();
4385         assertExpectException(SecurityException.class, null, () ->
4386                 dpm.setSystemSetting(admin1, Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, "0"));
4387     }
4388 
4389     @Test
testSetSystemSettingWithDO()4390     public void testSetSystemSettingWithDO() throws Exception {
4391         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4392         setupDeviceOwner();
4393         dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
4394         verify(getServices().settings).settingsSystemPutStringForUser(
4395                 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
4396     }
4397 
4398     @Test
testSetSystemSettingWithPO()4399     public void testSetSystemSettingWithPO() throws Exception {
4400         setupProfileOwner();
4401         dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
4402         verify(getServices().settings).settingsSystemPutStringForUser(
4403             Settings.System.SCREEN_BRIGHTNESS, "0", CALLER_USER_HANDLE);
4404     }
4405 
4406     @Test
4407     @Ignore("b/277916462")
testSetAutoTimeEnabledModifiesSetting()4408     public void testSetAutoTimeEnabledModifiesSetting() throws Exception {
4409         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4410         setupDeviceOwner();
4411         dpm.setAutoTimeEnabled(admin1, true);
4412         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
4413 
4414         dpm.setAutoTimeEnabled(admin1, false);
4415         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
4416     }
4417 
4418     @Test
4419     @Ignore("b/277916462")
testSetAutoTimeEnabledWithPOOnUser0()4420     public void testSetAutoTimeEnabledWithPOOnUser0() throws Exception {
4421         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4422         setupProfileOwnerOnUser0();
4423         dpm.setAutoTimeEnabled(admin1, true);
4424         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
4425 
4426         dpm.setAutoTimeEnabled(admin1, false);
4427         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
4428     }
4429 
4430     @Test
testSetAutoTimeEnabledFailWithPONotOnUser0()4431     public void testSetAutoTimeEnabledFailWithPONotOnUser0() throws Exception {
4432         setupProfileOwner();
4433         assertExpectException(SecurityException.class, null,
4434                 () -> dpm.setAutoTimeEnabled(admin1, false));
4435         verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
4436     }
4437 
4438     @Test
4439     @Ignore("b/277916462")
testSetAutoTimeEnabledWithPOOfOrganizationOwnedDevice()4440     public void testSetAutoTimeEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
4441         setupProfileOwner();
4442         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4443 
4444         dpm.setAutoTimeEnabled(admin1, true);
4445         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
4446 
4447         dpm.setAutoTimeEnabled(admin1, false);
4448         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
4449     }
4450 
4451     @Test
4452     @Ignore("b/277916462")
testSetAutoTimeZoneEnabledModifiesSetting()4453     public void testSetAutoTimeZoneEnabledModifiesSetting() throws Exception {
4454         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4455         setupDeviceOwner();
4456         dpm.setAutoTimeZoneEnabled(admin1, true);
4457         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
4458 
4459         dpm.setAutoTimeZoneEnabled(admin1, false);
4460         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
4461     }
4462 
4463     @Test
4464     @Ignore("b/277916462")
testSetAutoTimeZoneEnabledWithPOOnUser0()4465     public void testSetAutoTimeZoneEnabledWithPOOnUser0() throws Exception {
4466         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4467         setupProfileOwnerOnUser0();
4468         dpm.setAutoTimeZoneEnabled(admin1, true);
4469         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
4470 
4471         dpm.setAutoTimeZoneEnabled(admin1, false);
4472         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
4473     }
4474 
4475     @Test
4476     @Ignore("b/277916462")
testSetAutoTimeZoneEnabledFailWithPONotOnUser0()4477     public void testSetAutoTimeZoneEnabledFailWithPONotOnUser0() throws Exception {
4478         setupProfileOwner();
4479         assertExpectException(SecurityException.class, null,
4480                 () -> dpm.setAutoTimeZoneEnabled(admin1, false));
4481         verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE,
4482                 0);
4483     }
4484 
4485     @Test
4486     @Ignore("b/277916462")
testSetAutoTimeZoneEnabledWithPOOfOrganizationOwnedDevice()4487     public void testSetAutoTimeZoneEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
4488         setupProfileOwner();
4489         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4490 
4491         dpm.setAutoTimeZoneEnabled(admin1, true);
4492         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
4493 
4494         dpm.setAutoTimeZoneEnabled(admin1, false);
4495         verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
4496     }
4497 
4498     @Test
testIsOrganizationOwnedDevice()4499     public void testIsOrganizationOwnedDevice() throws Exception {
4500         // Set up the user manager to return correct user info
4501         addManagedProfile(admin1, DpmMockContext.CALLER_UID, admin1);
4502 
4503         // Any caller should be able to call this method.
4504         assertThat(dpm.isOrganizationOwnedDeviceWithManagedProfile()).isFalse();
4505         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4506 
4507         verify(getServices().userManager).setUserRestriction(
4508                 eq(UserManager.DISALLOW_ADD_USER),
4509                 eq(true),
4510                 eq(UserHandle.of(UserHandle.USER_SYSTEM)));
4511 
4512         assertThat(dpm.isOrganizationOwnedDeviceWithManagedProfile()).isTrue();
4513 
4514         // A random caller from another user should also be able to get the right result.
4515         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
4516         assertThat(dpm.isOrganizationOwnedDeviceWithManagedProfile()).isTrue();
4517     }
4518 
4519     @Test
testMarkOrganizationOwnedDevice_baseRestrictionsAdded()4520     public void testMarkOrganizationOwnedDevice_baseRestrictionsAdded() throws Exception {
4521         addManagedProfile(admin1, DpmMockContext.CALLER_UID, admin1);
4522 
4523         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4524 
4525         // Base restriction DISALLOW_REMOVE_MANAGED_PROFILE added
4526         verify(getServices().userManager).setUserRestriction(
4527                 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
4528                 eq(true),
4529                 eq(UserHandle.of(UserHandle.USER_SYSTEM)));
4530 
4531         // Base restriction DISALLOW_ADD_USER added
4532         verify(getServices().userManager).setUserRestriction(
4533                 eq(UserManager.DISALLOW_ADD_USER),
4534                 eq(true),
4535                 eq(UserHandle.of(UserHandle.USER_SYSTEM)));
4536 
4537         // Assert base restrictions cannot be added or removed by admin
4538         assertExpectException(SecurityException.class, null, () ->
4539                 parentDpm.addUserRestriction(admin1, UserManager.DISALLOW_REMOVE_MANAGED_PROFILE));
4540         assertExpectException(SecurityException.class, null, () ->
4541                 parentDpm.clearUserRestriction(admin1,
4542                         UserManager.DISALLOW_REMOVE_MANAGED_PROFILE));
4543         assertExpectException(SecurityException.class, null, () ->
4544                 parentDpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER));
4545         assertExpectException(SecurityException.class, null, () ->
4546                 parentDpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER));
4547     }
4548 
4549     @Test
testSetTime()4550     public void testSetTime() throws Exception {
4551         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4552         setupDeviceOwner();
4553         dpm.setTime(admin1, 0);
4554         verify(getServices().alarmManager).setTime(0);
4555     }
4556 
4557     @Test
testSetTimeFailWithPO()4558     public void testSetTimeFailWithPO() throws Exception {
4559         setupProfileOwner();
4560         assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
4561     }
4562 
4563     @Test
testSetTimeWithPOOfOrganizationOwnedDevice()4564     public void testSetTimeWithPOOfOrganizationOwnedDevice() throws Exception {
4565         setupProfileOwner();
4566         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4567         dpm.setTime(admin1, 0);
4568         verify(getServices().alarmManager).setTime(0);
4569     }
4570 
4571     @Test
testSetTimeWithAutoTimeOn()4572     public void testSetTimeWithAutoTimeOn() throws Exception {
4573         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4574         setupDeviceOwner();
4575         when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
4576                 .thenReturn(1);
4577         assertThat(dpm.setTime(admin1, 0)).isFalse();
4578     }
4579 
4580     @Test
testSetTimeZone()4581     public void testSetTimeZone() throws Exception {
4582         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4583         setupDeviceOwner();
4584         dpm.setTimeZone(admin1, "Asia/Shanghai");
4585         verify(getServices().alarmManagerInternal)
4586                 .setTimeZone(eq("Asia/Shanghai"), eq(TIME_ZONE_CONFIDENCE_HIGH), anyString());
4587     }
4588 
4589     @Test
testSetTimeZoneFailWithPO()4590     public void testSetTimeZoneFailWithPO() throws Exception {
4591         setupProfileOwner();
4592         assertExpectException(SecurityException.class, null,
4593                 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
4594     }
4595 
4596     @Test
testSetTimeZoneWithPOOfOrganizationOwnedDevice()4597     public void testSetTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
4598         setupProfileOwner();
4599         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4600         dpm.setTimeZone(admin1, "Asia/Shanghai");
4601         verify(getServices().alarmManagerInternal)
4602                 .setTimeZone(eq("Asia/Shanghai"), eq(TIME_ZONE_CONFIDENCE_HIGH), anyString());
4603     }
4604 
4605     @Test
testSetTimeZoneWithAutoTimeZoneOn()4606     public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
4607         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4608         setupDeviceOwner();
4609         when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
4610                 .thenReturn(1);
4611         assertThat(dpm.setTimeZone(admin1, "Asia/Shanghai")).isFalse();
4612     }
4613 
4614     @Test
testGetLastBugReportRequestTime()4615     public void testGetLastBugReportRequestTime() throws Exception {
4616         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4617         setupDeviceOwner();
4618 
4619         mContext.packageName = admin1.getPackageName();
4620         mContext.applicationInfo = new ApplicationInfo();
4621         when(mContext.resources.getColor(anyInt(), any())).thenReturn(Color.WHITE);
4622 
4623         // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4624         // feature is disabled because there are non-affiliated secondary users.
4625         getServices().removeUser(CALLER_USER_HANDLE);
4626 
4627         // No bug reports were requested so far.
4628         assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(-1);
4629 
4630         // Requesting a bug report should update the timestamp.
4631         final long beforeRequest = System.currentTimeMillis();
4632         dpm.requestBugreport(admin1);
4633         final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
4634         final long afterRequest = System.currentTimeMillis();
4635         assertThat(bugReportRequestTime).isAtLeast(beforeRequest);
4636         assertThat(bugReportRequestTime).isAtMost(afterRequest);
4637 
4638         // Checking the timestamp again should not change it.
4639         Thread.sleep(2);
4640         assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime);
4641 
4642         // Restarting the DPMS should not lose the timestamp.
4643         initializeDpms();
4644         assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime);
4645 
4646         // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4647         mContext.binder.callingUid = 1234567;
4648         mContext.callerPermissions.add(permission.MANAGE_USERS);
4649         assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime);
4650         mContext.callerPermissions.remove(permission.MANAGE_USERS);
4651 
4652         // System can retrieve the timestamp.
4653         mContext.binder.clearCallingIdentity();
4654         assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime);
4655 
4656         // Removing the device owner should clear the timestamp.
4657         clearDeviceOwner();
4658         assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(-1);
4659     }
4660 
4661     @Test
testGetLastNetworkLogRetrievalTime()4662     public void testGetLastNetworkLogRetrievalTime() throws Exception {
4663         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4664         setupDeviceOwner();
4665         mContext.packageName = admin1.getPackageName();
4666         mContext.applicationInfo = new ApplicationInfo();
4667         when(mContext.resources.getColor(anyInt(), any())).thenReturn(Color.WHITE);
4668 
4669         // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4670         // feature is disabled because there are non-affiliated secondary users.
4671         getServices().removeUser(CALLER_USER_HANDLE);
4672         when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), any()))
4673                 .thenReturn(true);
4674 
4675         // No logs were retrieved so far.
4676         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4677 
4678         // Attempting to retrieve logs without enabling logging should not change the timestamp.
4679         dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
4680         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4681 
4682         // Enabling logging should not change the timestamp.
4683         dpm.setNetworkLoggingEnabled(admin1, true);
4684         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4685 
4686         // Retrieving the logs should update the timestamp.
4687         final long beforeRetrieval = System.currentTimeMillis();
4688         dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
4689         final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
4690         final long afterRetrieval = System.currentTimeMillis();
4691         assertThat(firstNetworkLogRetrievalTime >= beforeRetrieval).isTrue();
4692         assertThat(firstNetworkLogRetrievalTime <= afterRetrieval).isTrue();
4693 
4694         // Checking the timestamp again should not change it.
4695         Thread.sleep(2);
4696         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(firstNetworkLogRetrievalTime);
4697 
4698         // Retrieving the logs again should update the timestamp.
4699         dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
4700         final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
4701         assertThat(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime).isTrue();
4702 
4703         // Disabling logging should not change the timestamp.
4704         Thread.sleep(2);
4705         dpm.setNetworkLoggingEnabled(admin1, false);
4706         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime);
4707 
4708         // Restarting the DPMS should not lose the timestamp.
4709         initializeDpms();
4710         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime);
4711 
4712         // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4713         mContext.binder.callingUid = 1234567;
4714         mContext.callerPermissions.add(permission.MANAGE_USERS);
4715         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime);
4716         mContext.callerPermissions.remove(permission.MANAGE_USERS);
4717 
4718         // System can retrieve the timestamp.
4719         mContext.binder.clearCallingIdentity();
4720         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime);
4721 
4722         // Removing the device owner should clear the timestamp.
4723         clearDeviceOwner();
4724         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4725     }
4726 
4727     @Test
testSetNetworkLoggingEnabled_asPo()4728     public void testSetNetworkLoggingEnabled_asPo() throws Exception {
4729         final int managedProfileUserId = CALLER_USER_HANDLE;
4730         final int managedProfileAdminUid =
4731                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
4732         mContext.binder.callingUid = managedProfileAdminUid;
4733         mContext.applicationInfo = new ApplicationInfo();
4734         mContext.packageName = admin1.getPackageName();
4735         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.S);
4736         when(getServices().iipConnectivityMetrics
4737                 .addNetdEventCallback(anyInt(), any())).thenReturn(true);
4738 
4739         // Check no logs have been retrieved so far.
4740         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4741 
4742         // Enable network logging
4743         dpm.setNetworkLoggingEnabled(admin1, true);
4744         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4745 
4746         // Retrieve the network logs and verify timestamp has been updated.
4747         final long beforeRetrieval = System.currentTimeMillis();
4748 
4749         dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
4750 
4751         final long networkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
4752         final long afterRetrieval = System.currentTimeMillis();
4753         assertThat(networkLogRetrievalTime >= beforeRetrieval).isTrue();
4754         assertThat(networkLogRetrievalTime <= afterRetrieval).isTrue();
4755     }
4756 
4757     @Test
testSetNetworkLoggingEnabled_asPoOfOrgOwnedDevice()4758     public void testSetNetworkLoggingEnabled_asPoOfOrgOwnedDevice() throws Exception {
4759         // Setup profile owner on organization-owned device
4760         final int MANAGED_PROFILE_ADMIN_UID =
4761                 UserHandle.getUid(CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
4762         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4763         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
4764 
4765         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4766         mContext.packageName = admin1.getPackageName();
4767         mContext.applicationInfo = new ApplicationInfo();
4768         when(getServices().iipConnectivityMetrics
4769                 .addNetdEventCallback(anyInt(), any())).thenReturn(true);
4770 
4771         // Check no logs have been retrieved so far.
4772         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4773 
4774         // Enable network logging
4775         dpm.setNetworkLoggingEnabled(admin1, true);
4776         assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1);
4777 
4778         // Retrieve the network logs and verify timestamp has been updated.
4779         final long beforeRetrieval = System.currentTimeMillis();
4780 
4781         dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
4782 
4783         final long networkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
4784         final long afterRetrieval = System.currentTimeMillis();
4785         assertThat(networkLogRetrievalTime >= beforeRetrieval).isTrue();
4786         assertThat(networkLogRetrievalTime <= afterRetrieval).isTrue();
4787     }
4788 
4789     @Test
testGetBindDeviceAdminTargetUsers()4790     public void testGetBindDeviceAdminTargetUsers() throws Exception {
4791         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
4792 
4793         // Setup device owner.
4794         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4795         setupDeviceOwner();
4796 
4797         // Only device owner is setup, the result list should be empty.
4798         List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4799         MoreAsserts.assertEmpty(targetUsers);
4800 
4801         // Add a secondary user, it should never talk with.
4802         final int ANOTHER_USER_ID = 36;
4803         getServices().addUser(ANOTHER_USER_ID, 0, UserManager.USER_TYPE_FULL_SECONDARY);
4804 
4805         // Since the managed profile is not affiliated, they should not be allowed to talk to each
4806         // other.
4807         targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4808         MoreAsserts.assertEmpty(targetUsers);
4809 
4810         // Setting affiliation ids
4811         final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
4812         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4813         dpm.setAffiliationIds(admin1, userAffiliationIds);
4814 
4815         // Changing affiliation ids in one
4816         dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
4817 
4818         // Since the managed profile is not affiliated any more, they should not be allowed to talk
4819         // to each other.
4820         targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4821         MoreAsserts.assertEmpty(targetUsers);
4822 
4823         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4824         targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4825         MoreAsserts.assertEmpty(targetUsers);
4826     }
4827 
verifyLockTaskState(int userId)4828     private void verifyLockTaskState(int userId) throws Exception {
4829         verifyLockTaskState(userId, new String[0],
4830                 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
4831     }
4832 
verifyLockTaskState(int userId, String[] packages, int flags)4833     private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
4834         verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
4835         verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
4836     }
4837 
verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages, int flags)4838     private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
4839             int flags) throws Exception {
4840         mContext.binder.callingUid = uid;
4841         dpm.setLockTaskPackages(who, packages);
4842         MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
4843         for (String p : packages) {
4844             assertThat(dpm.isLockTaskPermitted(p)).isTrue();
4845         }
4846         assertThat(dpm.isLockTaskPermitted("anotherPackage")).isFalse();
4847         // Test to see if set lock task features can be set
4848         dpm.setLockTaskFeatures(who, flags);
4849         verifyLockTaskState(userId, packages, flags);
4850     }
4851 
verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages, int flags)4852     private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
4853             int flags) throws Exception {
4854         mContext.binder.callingUid = uid;
4855         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4856                 () -> dpm.setLockTaskPackages(who, packages));
4857         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4858                 () -> dpm.getLockTaskPackages(who));
4859         assertThat(dpm.isLockTaskPermitted("doPackage1")).isFalse();
4860         assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4861                 () -> dpm.setLockTaskFeatures(who, flags));
4862     }
4863 
4864     @Test
4865     @FlakyTest(bugId = 260145949)
testLockTaskPolicyForProfileOwner()4866     public void testLockTaskPolicyForProfileOwner() throws Exception {
4867         mockPolicyExemptApps();
4868         mockVendorPolicyExemptApps();
4869 
4870         // Setup a PO
4871         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4872         setAsProfileOwner(admin1);
4873         verifyLockTaskState(CALLER_USER_HANDLE);
4874 
4875         final String[] poPackages = {"poPackage1", "poPackage2"};
4876         final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4877                 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4878                 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4879         verifyCanSetLockTask(DpmMockContext.CALLER_UID, CALLER_USER_HANDLE, admin1,
4880                 poPackages, poFlags);
4881 
4882         // Set up a managed profile managed by different package (package name shouldn't matter)
4883         final int MANAGED_PROFILE_USER_ID = 15;
4884         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
4885         final ComponentName adminDifferentPackage =
4886                 new ComponentName("another.package", "whatever.class");
4887         addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
4888         verifyLockTaskState(MANAGED_PROFILE_USER_ID);
4889 
4890         // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
4891         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4892         final String[] mpoPackages = {"poPackage1", "poPackage2"};
4893         final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4894                 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4895                 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4896         verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages,
4897                 mpoFlags);
4898     }
4899 
4900     @Test
4901     @FlakyTest(bugId = 260145949)
testLockTaskFeatures_IllegalArgumentException()4902     public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
4903         // Setup a device owner.
4904         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4905         setupDeviceOwner();
4906         // Lock task policy is updated when loading user data.
4907         verifyLockTaskState(UserHandle.USER_SYSTEM);
4908 
4909         final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4910                 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4911         assertExpectException(IllegalArgumentException.class,
4912                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
4913                 () -> dpm.setLockTaskFeatures(admin1, flags));
4914     }
4915 
4916     @Test
4917     @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
testSecondaryLockscreen_profileOwner()4918     public void testSecondaryLockscreen_profileOwner() throws Exception {
4919         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4920 
4921         // Initial state is disabled.
4922         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4923         CALLER_USER_HANDLE))).isFalse();
4924 
4925         // Profile owner can set enabled state.
4926         setAsProfileOwner(admin1);
4927         when(mServiceContext.resources
4928                 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4929                 .thenReturn(admin1.flattenToString());
4930         dpm.setSecondaryLockscreenEnabled(admin1, true);
4931         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4932         CALLER_USER_HANDLE))).isTrue();
4933 
4934         // Managed profile managed by different package is unaffiliated - cannot set enabled.
4935         final int managedProfileUserId = 15;
4936         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 20456);
4937         final ComponentName adminDifferentPackage =
4938                 new ComponentName("another.package", "whatever.class");
4939         addManagedProfile(adminDifferentPackage, managedProfileAdminUid, admin2);
4940         mContext.binder.callingUid = managedProfileAdminUid;
4941         assertExpectException(SecurityException.class, /* messageRegex= */ null,
4942                 () -> dpm.setSecondaryLockscreenEnabled(adminDifferentPackage, false));
4943     }
4944 
4945     @Test
4946     @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
testSecondaryLockscreen_deviceOwner()4947     public void testSecondaryLockscreen_deviceOwner() throws Exception {
4948         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4949 
4950         // Initial state is disabled.
4951         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM)))
4952                 .isFalse();
4953 
4954         // Device owners can set enabled state.
4955         setupDeviceOwner();
4956         when(mServiceContext.resources
4957                 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4958                 .thenReturn(admin1.flattenToString());
4959         dpm.setSecondaryLockscreenEnabled(admin1, true);
4960         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM)))
4961                 .isTrue();
4962     }
4963 
4964     @Test
4965     @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
testSecondaryLockscreen_nonOwner()4966     public void testSecondaryLockscreen_nonOwner() throws Exception {
4967         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4968 
4969         // Initial state is disabled.
4970         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse();
4971 
4972         // Non-DO/PO cannot set enabled state.
4973         when(mServiceContext.resources
4974                 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4975                 .thenReturn(admin1.flattenToString());
4976         assertExpectException(SecurityException.class, /* messageRegex= */ null,
4977                 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
4978         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse();
4979     }
4980 
4981     @Test
4982     @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
testSecondaryLockscreen_nonSupervisionApp()4983     public void testSecondaryLockscreen_nonSupervisionApp() throws Exception {
4984         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4985 
4986         // Ensure packages are *not* flagged as test_only.
4987         doReturn(new ApplicationInfo()).when(getServices().ipackageManager).getApplicationInfo(
4988                 eq(admin1.getPackageName()),
4989                 anyLong(),
4990                 eq(CALLER_USER_HANDLE));
4991         doReturn(new ApplicationInfo()).when(getServices().ipackageManager).getApplicationInfo(
4992                 eq(admin2.getPackageName()),
4993                 anyLong(),
4994                 eq(CALLER_USER_HANDLE));
4995 
4996         // Initial state is disabled.
4997         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse();
4998 
4999         // Caller is Profile Owner, but no supervision app is configured.
5000         setAsProfileOwner(admin1);
5001         assertExpectException(SecurityException.class, "is not the default supervision component",
5002                 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
5003         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse();
5004 
5005         // Caller is Profile Owner, but is not the default configured supervision app.
5006         when(mServiceContext.resources
5007                 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
5008                 .thenReturn(admin2.flattenToString());
5009         assertExpectException(SecurityException.class, "is not the default supervision component",
5010                 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
5011         assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse();
5012     }
5013 
5014     @Test
5015     @RequiresFlagsEnabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
testIsSecondaryLockscreenEnabled()5016     public void testIsSecondaryLockscreenEnabled() throws Exception {
5017         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5018 
5019         verifyIsSecondaryLockscreenEnabled(false);
5020         verifyIsSecondaryLockscreenEnabled(true);
5021     }
5022 
verifyIsSecondaryLockscreenEnabled(boolean expected)5023     private void verifyIsSecondaryLockscreenEnabled(boolean expected) throws Exception {
5024         reset(getServices().supervisionManagerInternal);
5025 
5026         doReturn(expected).when(getServices().supervisionManagerInternal)
5027                 .isSupervisionLockscreenEnabledForUser(anyInt());
5028 
5029         final boolean enabled = dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE));
5030         verify(getServices().supervisionManagerInternal)
5031                 .isSupervisionLockscreenEnabledForUser(CALLER_USER_HANDLE);
5032 
5033         assertThat(enabled).isEqualTo(expected);
5034     }
5035 
5036     @Test
5037     @RequiresFlagsEnabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
testSetSecondaryLockscreenEnabled()5038     public void testSetSecondaryLockscreenEnabled() throws Exception {
5039         verifySetSecondaryLockscreenEnabled(false);
5040         verifySetSecondaryLockscreenEnabled(true);
5041     }
5042 
verifySetSecondaryLockscreenEnabled(boolean enabled)5043     private void verifySetSecondaryLockscreenEnabled(boolean enabled) throws Exception {
5044         reset(getServices().supervisionManagerInternal);
5045 
5046         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5047         doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManagerInternal)
5048                 .getPackageUid(any(), anyLong(), anyInt());
5049 
5050         dpm.setSecondaryLockscreenEnabled(admin1, enabled);
5051         verify(getServices().supervisionManagerInternal).setSupervisionLockscreenEnabledForUser(
5052                 CALLER_USER_HANDLE, enabled, null);
5053 
5054         reset(getServices().supervisionManagerInternal);
5055 
5056         dpm.setSecondaryLockscreenEnabled(enabled, new PersistableBundle());
5057         verify(getServices().supervisionManagerInternal).setSupervisionLockscreenEnabledForUser(
5058                 eq(CALLER_USER_HANDLE), eq(enabled), any(PersistableBundle.class));
5059     }
5060 
5061     @Test
testIsDeviceManaged()5062     public void testIsDeviceManaged() throws Exception {
5063         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5064         setupDeviceOwner();
5065 
5066         // The device owner itself, any uid holding MANAGE_USERS permission and the system can
5067         // find out that the device has a device owner.
5068         assertThat(dpm.isDeviceManaged()).isTrue();
5069         mContext.binder.callingUid = 1234567;
5070         mContext.callerPermissions.add(permission.MANAGE_USERS);
5071         assertThat(dpm.isDeviceManaged()).isTrue();
5072         mContext.callerPermissions.remove(permission.MANAGE_USERS);
5073         mContext.binder.clearCallingIdentity();
5074         assertThat(dpm.isDeviceManaged()).isTrue();
5075 
5076         clearDeviceOwner();
5077 
5078         // Any uid holding MANAGE_USERS permission and the system can find out that the device does
5079         // not have a device owner.
5080         mContext.binder.callingUid = 1234567;
5081         mContext.callerPermissions.add(permission.MANAGE_USERS);
5082         assertThat(dpm.isDeviceManaged()).isFalse();
5083         mContext.callerPermissions.remove(permission.MANAGE_USERS);
5084         mContext.binder.clearCallingIdentity();
5085         assertThat(dpm.isDeviceManaged()).isFalse();
5086     }
5087 
5088     @Test
testDeviceOwnerOrganizationName()5089     public void testDeviceOwnerOrganizationName() throws Exception {
5090         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5091         setupDeviceOwner();
5092 
5093         dpm.setOrganizationName(admin1, "organization");
5094 
5095         // Device owner can retrieve organization managing the device.
5096         assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo("organization");
5097 
5098         // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
5099         mContext.binder.callingUid = 1234567;
5100         mContext.callerPermissions.add(permission.MANAGE_USERS);
5101         assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo("organization");
5102         mContext.callerPermissions.remove(permission.MANAGE_USERS);
5103 
5104         // System can retrieve organization managing the device.
5105         mContext.binder.clearCallingIdentity();
5106         assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo("organization");
5107 
5108         // Removing the device owner clears the organization managing the device.
5109         clearDeviceOwner();
5110         assertThat(dpm.getDeviceOwnerOrganizationName()).isNull();
5111     }
5112 
5113     @Test
testWipeDataManagedProfile()5114     public void testWipeDataManagedProfile() throws Exception {
5115         final int MANAGED_PROFILE_USER_ID = 15;
5116         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5117         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5118         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5119         mServiceContext.permissions.add(permission.INTERACT_ACROSS_USERS_FULL);
5120 
5121         // Even if the caller is the managed profile, the current user is the user 0
5122         when(getServices().iactivityManager.getCurrentUser())
5123                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5124         // Get mock reason string since we throw an IAE with empty string input.
5125         when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe))
5126                 .thenReturn("Just a test string.");
5127 
5128         dpm.wipeData(0);
5129         verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
5130                 MANAGED_PROFILE_USER_ID);
5131     }
5132 
5133     @Test
5134     @Ignore("b/277916462")
testWipeDataManagedProfileOnOrganizationOwnedDevice()5135     public void testWipeDataManagedProfileOnOrganizationOwnedDevice() throws Exception {
5136         setupProfileOwner();
5137         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
5138         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
5139                 FLAG_ENABLE_WORK_PROFILE_TELEPHONY, "true", false);
5140         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TELEPHONY,
5141                 FLAG_ENABLE_WORK_PROFILE_TELEPHONY, "true", false);
5142         // Even if the caller is the managed profile, the current user is the user 0
5143         when(getServices().iactivityManager.getCurrentUser())
5144                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5145         // Get mock reason string since we throw an IAE with empty string input.
5146         when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe))
5147                 .thenReturn("Just a test string.");
5148         when(getServices().userManager.getProfileParent(CALLER_USER_HANDLE))
5149                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5150         when(getServices().userManager.getPrimaryUser())
5151                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5152         when(getServices().subscriptionManager.getActiveSubscriptionIdList(false)).thenReturn(
5153                 new int[1]);
5154         // Set some device-wide policies:
5155         // Security logging
5156         when(getServices().settings.securityLogGetLoggingEnabledProperty()).thenReturn(true);
5157         // System update policy
5158         dpms.mOwners.setSystemUpdatePolicy(SystemUpdatePolicy.createAutomaticInstallPolicy());
5159         // Make it look as if FRP agent is present.
5160         when(dpms.mMockInjector.getPersistentDataBlockManagerInternal().getAllowedUid())
5161                 .thenReturn(12345 /* some UID in user 0 */);
5162         // Make personal apps look suspended
5163         dpms.getUserData(UserHandle.USER_SYSTEM).mAppsSuspended = true;
5164         // Screen capture
5165         dpm.setScreenCaptureDisabled(admin1, true);
5166 
5167         dpm.wipeData(0);
5168         verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(CALLER_USER_HANDLE);
5169 
5170         // Make sure COPE restrictions are lifted:
5171         verify(getServices().userManager).setUserRestriction(
5172                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, UserHandle.SYSTEM);
5173         verify(getServices().userManager).setUserRestriction(
5174                 UserManager.DISALLOW_ADD_USER, false, UserHandle.SYSTEM);
5175 
5176         clearInvocations(getServices().iwindowManager);
5177 
5178         // Some device-wide policies are getting cleaned-up after the user is removed.
5179         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5180         sendBroadcastWithUser(dpms, Intent.ACTION_USER_REMOVED, CALLER_USER_HANDLE);
5181 
5182         // Screenlock info should be removed
5183         verify(getServices().lockPatternUtils).setDeviceOwnerInfo(null);
5184         // Wifi config lockdown should be lifted
5185         verify(getServices().settings).settingsGlobalPutInt(
5186                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
5187         // System update policy should be removed
5188         assertThat(dpms.mOwners.getSystemUpdatePolicy()).isNull();
5189         // FRP agent should be notified
5190         verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
5191                 MockUtils.checkIntentAction(
5192                         DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
5193                 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
5194         // Refresh strong auth timeout
5195         verify(getServices().lockSettingsInternal).refreshStrongAuthTimeout(UserHandle.USER_SYSTEM);
5196         // Refresh screen capture
5197         verify(getServices().iwindowManager).refreshScreenCaptureDisabled();
5198         // Unsuspend personal apps
5199         verify(getServices().packageManagerInternal)
5200                 .unsuspendAdminSuspendedPackages(UserHandle.USER_SYSTEM);
5201         verify(getServices().subscriptionManager).setSubscriptionUserHandle(0, null);
5202         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
5203                 FLAG_ENABLE_WORK_PROFILE_TELEPHONY, "false", false);
5204         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TELEPHONY,
5205                 FLAG_ENABLE_WORK_PROFILE_TELEPHONY, "false", false);
5206     }
5207 
5208     @Test
testWipeDataManagedProfileDisallowed()5209     public void testWipeDataManagedProfileDisallowed() throws Exception {
5210         final int MANAGED_PROFILE_USER_ID = 15;
5211         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5212         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5213 
5214         // Even if the caller is the managed profile, the current user is the user 0
5215         when(getServices().iactivityManager.getCurrentUser())
5216                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5217 
5218         when(getServices().userManager.getUserRestrictionSource(
5219                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
5220                 UserHandle.of(MANAGED_PROFILE_USER_ID)))
5221                 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
5222         when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
5223                 thenReturn("Just a test string.");
5224 
5225         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5226         // The PO is not allowed to remove the profile if the user restriction was set on the
5227         // profile by the system
5228         assertExpectException(SecurityException.class, /* messageRegex= */ null,
5229                 () -> dpm.wipeData(0));
5230     }
5231 
5232     @Test
testWipeDevice_DeviceOwner()5233     public void testWipeDevice_DeviceOwner() throws Exception {
5234         setDeviceOwner();
5235         when(getServices().userManager.getUserRestrictionSource(
5236                 UserManager.DISALLOW_FACTORY_RESET,
5237                 UserHandle.SYSTEM))
5238                 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
5239         when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
5240                 thenReturn("Just a test string.");
5241 
5242         dpm.wipeDevice(0);
5243 
5244         verifyRebootWipeUserData(/* wipeEuicc= */ false);
5245     }
5246 
5247     @Test
testWipeEuiccDataEnabled()5248     public void testWipeEuiccDataEnabled() throws Exception {
5249         setDeviceOwner();
5250         when(getServices().userManager.getUserRestrictionSource(
5251             UserManager.DISALLOW_FACTORY_RESET,
5252             UserHandle.SYSTEM))
5253             .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
5254         when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
5255                 thenReturn("Just a test string.");
5256 
5257         dpm.wipeDevice(WIPE_EUICC);
5258 
5259         verifyRebootWipeUserData(/* wipeEuicc= */ true);
5260     }
5261 
5262     @Test
testWipeDevice_DeviceOwnerDisallowed()5263     public void testWipeDevice_DeviceOwnerDisallowed() throws Exception {
5264         setDeviceOwner();
5265         when(getServices().userManager.getUserRestrictionSource(
5266                 UserManager.DISALLOW_FACTORY_RESET,
5267                 UserHandle.SYSTEM))
5268                 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
5269         when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
5270                 thenReturn("Just a test string.");
5271         // The DO is not allowed to wipe the device if the user restriction was set
5272         // by the system
5273         assertExpectException(SecurityException.class, /* messageRegex= */ null,
5274                 () -> dpm.wipeDevice(0));
5275     }
5276 
5277     @Test
testMaximumFailedPasswordAttemptsReachedManagedProfile()5278     public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
5279         final int MANAGED_PROFILE_USER_ID = 15;
5280         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5281         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5282 
5283         // Even if the caller is the managed profile, the current user is the user 0
5284         when(getServices().iactivityManager.getCurrentUser())
5285                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5286 
5287         when(getServices().userManager.getUserRestrictionSource(
5288                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
5289                 UserHandle.of(MANAGED_PROFILE_USER_ID)))
5290                 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
5291 
5292         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5293         dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
5294 
5295         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5296         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
5297         // Failed password attempts on the parent user are taken into account, as there isn't a
5298         // separate work challenge.
5299         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5300         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5301         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5302 
5303         // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
5304         // both the user restriction and the policy were set by the PO.
5305         verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
5306                 MANAGED_PROFILE_USER_ID);
5307         verifyNoMoreInteractions(getServices().recoverySystem);
5308     }
5309 
5310     @Test
testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()5311     public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
5312             throws Exception {
5313         final int MANAGED_PROFILE_USER_ID = 15;
5314         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5315         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5316 
5317         // Even if the caller is the managed profile, the current user is the user 0
5318         when(getServices().iactivityManager.getCurrentUser())
5319                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5320 
5321         when(getServices().userManager.getUserRestrictionSource(
5322                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
5323                 UserHandle.of(MANAGED_PROFILE_USER_ID)))
5324                 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
5325 
5326         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5327         dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
5328 
5329         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5330         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
5331         // Failed password attempts on the parent user are taken into account, as there isn't a
5332         // separate work challenge.
5333         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5334         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5335         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5336 
5337         // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
5338         // not wiped.
5339         verify(getServices().userManagerInternal, never())
5340                 .removeUserEvenWhenDisallowed(anyInt());
5341         verifyNoMoreInteractions(getServices().recoverySystem);
5342     }
5343 
5344     @Test
testMaximumFailedPasswordAttemptsReachedDeviceOwner()5345     public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
5346         setDeviceOwner();
5347         when(getServices().userManager.getUserRestrictionSource(
5348                 UserManager.DISALLOW_FACTORY_RESET,
5349                 UserHandle.SYSTEM))
5350                 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
5351 
5352         dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
5353 
5354         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5355         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
5356         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5357         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5358         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5359 
5360         // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
5361         // user restriction and the policy were set by the DO.
5362         verifyRebootWipeUserData(/* wipeEuicc= */ false);
5363     }
5364 
5365     @Test
testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed()5366     public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
5367         setDeviceOwner();
5368         when(getServices().userManager.getUserRestrictionSource(
5369                 UserManager.DISALLOW_FACTORY_RESET,
5370                 UserHandle.SYSTEM))
5371                 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
5372 
5373         dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
5374 
5375         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5376         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
5377         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5378         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5379         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5380 
5381         // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
5382         verifyNoMoreInteractions(getServices().recoverySystem);
5383         verify(getServices().userManagerInternal, never())
5384                 .removeUserEvenWhenDisallowed(anyInt());
5385     }
5386 
5387     @Test
testMaximumFailedDevicePasswordAttemptsReachedOrgOwnedManagedProfile()5388     public void testMaximumFailedDevicePasswordAttemptsReachedOrgOwnedManagedProfile()
5389             throws Exception {
5390         final int MANAGED_PROFILE_USER_ID = 15;
5391         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5392         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5393 
5394         // Even if the caller is the managed profile, the current user is the user 0
5395         when(getServices().iactivityManager.getCurrentUser())
5396                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5397 
5398         configureProfileOwnerOfOrgOwnedDevice(admin1, MANAGED_PROFILE_USER_ID);
5399 
5400         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5401         dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
5402 
5403         assertThat(dpm.getMaximumFailedPasswordsForWipe(admin1)).isEqualTo(3);
5404         assertThat(dpm.getMaximumFailedPasswordsForWipe(null)).isEqualTo(3);
5405 
5406         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5407         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
5408 
5409         assertThat(dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM)).isEqualTo(3);
5410         // Check that primary will be wiped as a result of failed primary user unlock attempts.
5411         assertThat(dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM))
5412                 .isEqualTo(UserHandle.USER_SYSTEM);
5413 
5414         // Failed password attempts on the parent user are taken into account, as there isn't a
5415         // separate work challenge.
5416         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5417         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5418         dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
5419 
5420         // For managed profile on an organization owned device, the whole device should be wiped.
5421         verifyRebootWipeUserData(/* wipeEuicc= */ false);
5422     }
5423 
5424     @Test
testMaximumFailedProfilePasswordAttemptsReachedOrgOwnedManagedProfile()5425     public void testMaximumFailedProfilePasswordAttemptsReachedOrgOwnedManagedProfile()
5426             throws Exception {
5427         final int MANAGED_PROFILE_USER_ID = 15;
5428         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5429         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5430 
5431         // Even if the caller is the managed profile, the current user is the user 0
5432         when(getServices().iactivityManager.getCurrentUser())
5433                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
5434 
5435         doReturn(true).when(getServices().lockPatternUtils)
5436                 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
5437 
5438         // Configure separate challenge.
5439         configureProfileOwnerOfOrgOwnedDevice(admin1, MANAGED_PROFILE_USER_ID);
5440 
5441         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5442         dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
5443 
5444         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5445         mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
5446 
5447         assertThat(dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM)).isEqualTo(0);
5448         assertThat(dpm.getMaximumFailedPasswordsForWipe(null, MANAGED_PROFILE_USER_ID))
5449                 .isEqualTo(3);
5450         // Check that the policy is not affecting primary profile challenge.
5451         assertThat(dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM))
5452                 .isEqualTo(UserHandle.USER_NULL);
5453         // Check that primary will be wiped as a result of failed profile unlock attempts.
5454         assertThat(dpm.getProfileWithMinimumFailedPasswordsForWipe(MANAGED_PROFILE_USER_ID))
5455                 .isEqualTo(UserHandle.USER_SYSTEM);
5456 
5457         // Simulate three failed attempts at solving the separate challenge.
5458         dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID);
5459         dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID);
5460         dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID);
5461 
5462         // For managed profile on an organization owned device, the whole device should be wiped.
5463         verifyRebootWipeUserData(/* wipeEuicc= */ false);
5464     }
5465 
5466     @Test
testGetPermissionGrantState()5467     public void testGetPermissionGrantState() throws Exception {
5468         final String permission = "some.permission";
5469         final String app1 = "com.example.app1";
5470         final String app2 = "com.example.app2";
5471 
5472         when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
5473                 .thenReturn(PackageManager.PERMISSION_GRANTED);
5474         doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
5475                 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
5476         when(getServices().packageManager.getPermissionFlags(permission, app1,
5477                 UserHandle.of(CALLER_USER_HANDLE)))
5478                 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
5479         when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
5480                 .thenReturn(PackageManager.PERMISSION_DENIED);
5481         doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
5482                 UserHandle.SYSTEM);
5483         when(getServices().packageManager.getPermissionFlags(permission, app2,
5484                 UserHandle.of(CALLER_USER_HANDLE))).thenReturn(0);
5485 
5486         // System can retrieve permission grant state.
5487         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5488         mContext.packageName = "android";
5489         assertThat(dpm.getPermissionGrantState(null, app1, permission))
5490                 .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);
5491         assertThat(dpm.getPermissionGrantState(null, app2, permission))
5492                 .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
5493 
5494         // A regular app cannot retrieve permission grant state.
5495         mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
5496         mContext.packageName = app1;
5497         assertExpectException(SecurityException.class, /* messageRegex= */ null,
5498                 () -> dpm.getPermissionGrantState(null, app1, permission));
5499 
5500         // Profile owner can retrieve permission grant state.
5501         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5502         mContext.packageName = admin1.getPackageName();
5503         setAsProfileOwner(admin1);
5504         assertThat(dpm.getPermissionGrantState(admin1, app1, permission))
5505                 .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);
5506         assertThat(dpm.getPermissionGrantState(admin1, app2, permission))
5507                 .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
5508     }
5509 
5510     @Test
5511     @Ignore("b/277916462")
testResetPasswordWithToken()5512     public void testResetPasswordWithToken() throws Exception {
5513         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5514         setupDeviceOwner();
5515         // test token validation
5516         assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
5517                 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
5518 
5519         // test adding a token
5520         final byte[] token = new byte[32];
5521         final long handle = 123456;
5522         final String password = "password";
5523         when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
5524                 nullable(EscrowTokenStateChangeCallback.class)))
5525                 .thenReturn(handle);
5526         assertThat(dpm.setResetPasswordToken(admin1, token)).isTrue();
5527 
5528         // test password activation
5529         when(getServices().lockPatternUtils.isEscrowTokenActive(handle, UserHandle.USER_SYSTEM))
5530                 .thenReturn(true);
5531         assertThat(dpm.isResetPasswordTokenActive(admin1)).isTrue();
5532 
5533         // test reset password with token
5534         when(getServices().lockPatternUtils.setLockCredentialWithToken(
5535                 LockscreenCredential.createPassword(password), handle, token,
5536                 UserHandle.USER_SYSTEM)).thenReturn(true);
5537         assertThat(dpm.resetPasswordWithToken(admin1, password, token, 0)).isTrue();
5538 
5539         // test removing a token
5540         when(getServices().lockPatternUtils.removeEscrowToken(handle, UserHandle.USER_SYSTEM))
5541                 .thenReturn(true);
5542         assertThat(dpm.clearResetPasswordToken(admin1)).isTrue();
5543     }
5544 
5545     @Test
5546     @Ignore("b/277916462")
resetPasswordWithToken_NumericPin()5547     public void resetPasswordWithToken_NumericPin() throws Exception {
5548         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5549         setupDeviceOwner();
5550         // adding a token
5551         final byte[] token = new byte[32];
5552         final long handle = 123456;
5553         when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
5554                 nullable(EscrowTokenStateChangeCallback.class)))
5555                 .thenReturn(handle);
5556         assertThat(dpm.setResetPasswordToken(admin1, token)).isTrue();
5557 
5558         // Test resetting with a numeric pin
5559         final String pin = "123456";
5560         when(getServices().lockPatternUtils.setLockCredentialWithToken(
5561                 LockscreenCredential.createPin(pin), handle, token,
5562                 UserHandle.USER_SYSTEM)).thenReturn(true);
5563         assertThat(dpm.resetPasswordWithToken(admin1, pin, token, 0)).isTrue();
5564     }
5565 
5566     @Test
5567     @Ignore("b/277916462")
resetPasswordWithToken_EmptyPassword()5568     public void resetPasswordWithToken_EmptyPassword() throws Exception {
5569         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5570         setupDeviceOwner();
5571         // adding a token
5572         final byte[] token = new byte[32];
5573         final long handle = 123456;
5574         when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
5575                 nullable(EscrowTokenStateChangeCallback.class)))
5576                 .thenReturn(handle);
5577         assertThat(dpm.setResetPasswordToken(admin1, token)).isTrue();
5578 
5579         // Test resetting with an empty password
5580         final String password = "";
5581         when(getServices().lockPatternUtils.setLockCredentialWithToken(
5582                 LockscreenCredential.createNone(), handle, token,
5583                 UserHandle.USER_SYSTEM)).thenReturn(true);
5584         assertThat(dpm.resetPasswordWithToken(admin1, password, token, 0)).isTrue();
5585     }
5586 
5587     @Test
testIsActivePasswordSufficient()5588     public void testIsActivePasswordSufficient() throws Exception {
5589         assumeDeprecatedPasswordApisSupported();
5590 
5591         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5592         mContext.packageName = admin1.getPackageName();
5593         setupDeviceOwner();
5594 
5595         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
5596         dpm.setPasswordMinimumLength(admin1, 8);
5597         dpm.setPasswordMinimumLetters(admin1, 6);
5598         dpm.setPasswordMinimumLowerCase(admin1, 3);
5599         dpm.setPasswordMinimumUpperCase(admin1, 1);
5600         dpm.setPasswordMinimumNonLetter(admin1, 1);
5601         dpm.setPasswordMinimumNumeric(admin1, 1);
5602         dpm.setPasswordMinimumSymbols(admin1, 0);
5603 
5604         reset(mContext.spiedContext);
5605 
5606         PasswordMetrics passwordMetricsNoSymbols = metricsForPassword("abcdXYZ5");
5607 
5608         setActivePasswordState(passwordMetricsNoSymbols);
5609         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5610 
5611         initializeDpms();
5612         reset(mContext.spiedContext);
5613         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5614 
5615         // This call simulates the user entering the password for the first time after a reboot.
5616         // This causes password metrics to be reloaded into memory.  Until this happens,
5617         // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
5618         // even if the DPC changes password requirements so that the password no longer meets the
5619         // requirements.  This is a known limitation of the current implementation of
5620         // isActivePasswordSufficient() - see b/34218769.
5621         setActivePasswordState(passwordMetricsNoSymbols);
5622         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5623 
5624         dpm.setPasswordMinimumSymbols(admin1, 1);
5625         // This assertion would fail if we had not called setActivePasswordState() again after
5626         // initializeDpms() - see previous comment.
5627         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5628 
5629         initializeDpms();
5630         reset(mContext.spiedContext);
5631         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5632 
5633         PasswordMetrics passwordMetricsWithSymbols = metricsForPassword("abcd.XY5");
5634 
5635         setActivePasswordState(passwordMetricsWithSymbols);
5636         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5637     }
5638 
5639     @Test
testIsActivePasswordSufficient_noLockScreen()5640     public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
5641         assumeDeprecatedPasswordApisSupported();
5642 
5643         // If there is no lock screen, the password is considered empty no matter what, because
5644         // it provides no security.
5645         when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
5646 
5647         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5648         mContext.packageName = admin1.getPackageName();
5649         setupDeviceOwner();
5650         final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
5651         // When there is no lockscreen, user password metrics is always empty.
5652         when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
5653                 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
5654 
5655         // If no password requirements are set, isActivePasswordSufficient should succeed.
5656         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5657 
5658         // Now set some password quality requirements.
5659         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
5660 
5661         reset(mContext.spiedContext);
5662         // This should be ignored, as there is no lock screen.
5663         dpm.reportPasswordChanged(new PasswordMetrics(CREDENTIAL_TYPE_NONE), userHandle);
5664 
5665         // No broadcast should be sent.
5666         verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
5667                 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
5668                 MockUtils.checkUserHandle(userHandle));
5669 
5670         // The active (nonexistent) password doesn't comply with the requirements.
5671         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5672     }
5673 
5674     @Test
testIsPasswordSufficientAfterProfileUnification()5675     public void testIsPasswordSufficientAfterProfileUnification() throws Exception {
5676         final int managedProfileUserId = CALLER_USER_HANDLE;
5677         final int managedProfileAdminUid =
5678                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
5679         mContext.binder.callingUid = managedProfileAdminUid;
5680 
5681         addManagedProfile(admin1, managedProfileAdminUid, admin1);
5682         doReturn(true).when(getServices().lockPatternUtils)
5683                 .isSeparateProfileChallengeEnabled(managedProfileUserId);
5684 
5685         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
5686         parentDpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_MEDIUM);
5687 
5688         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5689                 .thenReturn(metricsForPin("184342"));
5690 
5691         // Numeric password is compliant with current requirement (QUALITY_NUMERIC set explicitly
5692         // on the parent admin)
5693         assertThat(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM,
5694         UserHandle.USER_NULL)).isTrue();
5695         // Numeric password is not compliant if profile is to be unified: the profile has a
5696         // QUALITY_ALPHABETIC policy on itself which will be enforced on the password after
5697         // unification.
5698         assertThat(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM,
5699         managedProfileUserId)).isFalse();
5700     }
5701 
5702     @Test
testGetAggregatedPasswordComplexity_IgnoreProfileRequirement()5703     public void testGetAggregatedPasswordComplexity_IgnoreProfileRequirement()
5704             throws Exception {
5705         final int managedProfileUserId = CALLER_USER_HANDLE;
5706         final int managedProfileAdminUid =
5707                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
5708         mContext.binder.callingUid = managedProfileAdminUid;
5709         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
5710 
5711         // Profile has a unified challenge
5712         doReturn(false).when(getServices().lockPatternUtils)
5713                 .isSeparateProfileChallengeEnabled(managedProfileUserId);
5714         doReturn(true).when(getServices().lockPatternUtils)
5715                 .isProfileWithUnifiedChallenge(managedProfileUserId);
5716 
5717         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
5718         parentDpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW);
5719 
5720         assertThat(dpms.getAggregatedPasswordComplexityForUser(UserHandle.USER_SYSTEM, true))
5721                 .isEqualTo(PASSWORD_COMPLEXITY_LOW);
5722         assertThat(dpms.getAggregatedPasswordComplexityForUser(UserHandle.USER_SYSTEM, false))
5723                 .isEqualTo(PASSWORD_COMPLEXITY_HIGH);
5724     }
5725 
5726     @Test
testGetAggregatedPasswordMetrics_IgnoreProfileRequirement()5727     public void testGetAggregatedPasswordMetrics_IgnoreProfileRequirement()
5728             throws Exception {
5729         assumeDeprecatedPasswordApisSupported();
5730 
5731         final int managedProfileUserId = CALLER_USER_HANDLE;
5732         final int managedProfileAdminUid =
5733                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
5734         mContext.binder.callingUid = managedProfileAdminUid;
5735         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
5736 
5737         // Profile has a unified challenge
5738         doReturn(false).when(getServices().lockPatternUtils)
5739                 .isSeparateProfileChallengeEnabled(managedProfileUserId);
5740         doReturn(true).when(getServices().lockPatternUtils)
5741                 .isProfileWithUnifiedChallenge(managedProfileUserId);
5742 
5743         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
5744         dpm.setPasswordMinimumLength(admin1, 8);
5745         dpm.setPasswordMinimumLetters(admin1, 1);
5746         dpm.setPasswordMinimumNumeric(admin1, 2);
5747         dpm.setPasswordMinimumSymbols(admin1, 3);
5748 
5749         parentDpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
5750 
5751         PasswordMetrics deviceMetrics =
5752                 dpms.getPasswordMinimumMetrics(UserHandle.USER_SYSTEM, true);
5753         assertThat(deviceMetrics.credType).isEqualTo(LockPatternUtils.CREDENTIAL_TYPE_PATTERN);
5754 
5755         PasswordMetrics allMetrics =
5756                 dpms.getPasswordMinimumMetrics(UserHandle.USER_SYSTEM, false);
5757         assertThat(allMetrics.credType).isEqualTo(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD);
5758         assertThat(allMetrics.length).isEqualTo(8);
5759         assertThat(allMetrics.letters).isEqualTo(1);
5760         assertThat(allMetrics.numeric).isEqualTo(2);
5761         assertThat(allMetrics.symbols).isEqualTo(3);
5762     }
5763 
5764     @Test
testCanSetPasswordRequirementOnParentPreS()5765     public void testCanSetPasswordRequirementOnParentPreS() throws Exception {
5766         assumeDeprecatedPasswordApisSupported();
5767 
5768         final int managedProfileUserId = CALLER_USER_HANDLE;
5769         final int managedProfileAdminUid =
5770                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
5771         mContext.binder.callingUid = managedProfileAdminUid;
5772         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
5773         dpms.mMockInjector.setChangeEnabledForPackage(165573442L, false,
5774                 admin1.getPackageName(), managedProfileUserId);
5775 
5776         parentDpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
5777         assertThat(parentDpm.getPasswordQuality(admin1))
5778                 .isEqualTo(DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
5779     }
5780 
5781     @Test
testCannotSetPasswordRequirementOnParent()5782     public void testCannotSetPasswordRequirementOnParent() throws Exception {
5783         assumeDeprecatedPasswordApisSupported();
5784 
5785         final int managedProfileUserId = CALLER_USER_HANDLE;
5786         final int managedProfileAdminUid =
5787                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
5788         mContext.binder.callingUid = managedProfileAdminUid;
5789         addManagedProfile(admin1, managedProfileAdminUid, admin1);
5790         dpms.mMockInjector.setChangeEnabledForPackage(165573442L, true,
5791                 admin1.getPackageName(), managedProfileUserId);
5792 
5793         try {
5794             assertExpectException(SecurityException.class, null, () ->
5795                     parentDpm.setPasswordQuality(
5796                             admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX));
5797         } finally {
5798             dpms.mMockInjector.clearEnabledChanges();
5799         }
5800     }
5801 
5802     @Test
isActivePasswordSufficient_SeparateWorkChallenge_ProfileQualityRequirementMet()5803     public void isActivePasswordSufficient_SeparateWorkChallenge_ProfileQualityRequirementMet()
5804             throws Exception {
5805         assumeDeprecatedPasswordApisSupported();
5806 
5807         // Create work profile with empty separate challenge
5808         final int managedProfileUserId = 15;
5809         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5810         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5811                 /* separateChallenge */ true);
5812 
5813         // Set profile password quality requirement. No password added yet so
5814         // profile.isActivePasswordSufficient should return false
5815         mContext.binder.callingUid = managedProfileAdminUid;
5816         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
5817         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5818         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5819 
5820         // Set a work challenge and verify profile.isActivePasswordSufficient is now true
5821         when(getServices().lockSettingsInternal.getUserPasswordMetrics(managedProfileUserId))
5822                 .thenReturn(metricsForPassword("abcdXYZ5"));
5823         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5824         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5825     }
5826 
5827     @Test
isActivePasswordSufficient_SeparateWorkChallenge_ProfileComplexityRequirementMet()5828     public void isActivePasswordSufficient_SeparateWorkChallenge_ProfileComplexityRequirementMet()
5829             throws Exception {
5830         assumeDeprecatedPasswordApisSupported();
5831 
5832         // Create work profile with empty separate challenge
5833         final int managedProfileUserId = 15;
5834         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5835         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5836                 /* separateChallenge */ true);
5837 
5838         // Set profile password complexity requirement. No password added yet so
5839         // profile.isActivePasswordSufficient should return false
5840         mContext.binder.callingUid = managedProfileAdminUid;
5841         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_MEDIUM);
5842         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5843         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5844 
5845         // Set a work challenge and verify profile.isActivePasswordSufficient is now true
5846         when(getServices().lockSettingsInternal.getUserPasswordMetrics(managedProfileUserId))
5847                 .thenReturn(metricsForPin("5156"));
5848         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5849         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5850     }
5851 
5852     @Test
isActivePasswordSufficient_SeparateWorkChallenge_ParentQualityRequirementMet()5853     public void isActivePasswordSufficient_SeparateWorkChallenge_ParentQualityRequirementMet()
5854             throws Exception {
5855         assumeDeprecatedPasswordApisSupported();
5856 
5857         // Create work profile with empty separate challenge
5858         final int managedProfileUserId = 15;
5859         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5860         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5861                 /* separateChallenge */ true);
5862 
5863         // Set parent password quality requirement. No password added yet so
5864         // parent.isActivePasswordSufficient should return false
5865         mContext.binder.callingUid = managedProfileAdminUid;
5866         parentDpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX);
5867         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5868         assertThat(parentDpm.isActivePasswordSufficient()).isFalse();
5869 
5870         // Set a device lockscreen and verify parent.isActivePasswordSufficient is now true
5871         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5872                 .thenReturn(metricsForPassword("acbdXYZ5"));
5873         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5874         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5875     }
5876 
5877     @Test
isActivePasswordSufficient_SeparateWorkChallenge_ParentComplexityRequirementMet()5878     public void isActivePasswordSufficient_SeparateWorkChallenge_ParentComplexityRequirementMet()
5879             throws Exception {
5880         // Create work profile with empty separate challenge
5881         final int managedProfileUserId = 15;
5882         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5883         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5884                 /* separateChallenge */ true);
5885 
5886         // Set parent password complexity requirement. No password added yet so
5887         // parent.isActivePasswordSufficient should return false
5888         mContext.binder.callingUid = managedProfileAdminUid;
5889         parentDpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW);
5890         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5891         assertThat(parentDpm.isActivePasswordSufficient()).isFalse();
5892 
5893         // Set a device lockscreen and verify parent.isActivePasswordSufficient is now true
5894         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5895                 .thenReturn(metricsForPin("1234"));
5896         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5897         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5898     }
5899 
5900     @Test
isActivePasswordSufficient_UnifiedWorkChallenge_ProfileQualityRequirementMet()5901     public void isActivePasswordSufficient_UnifiedWorkChallenge_ProfileQualityRequirementMet()
5902             throws Exception {
5903         assumeDeprecatedPasswordApisSupported();
5904 
5905         // Create work profile with unified challenge
5906         final int managedProfileUserId = 15;
5907         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5908         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5909                 /* separateChallenge */ false);
5910 
5911         // Set profile password quality requirement. No password added yet so
5912         // {profile, parent}.isActivePasswordSufficient should return false
5913         mContext.binder.callingUid = managedProfileAdminUid;
5914         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
5915         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5916         assertThat(parentDpm.isActivePasswordSufficient()).isFalse();
5917 
5918         // Set a device lockscreen and verify {profile, parent}.isActivePasswordSufficient is true
5919         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5920                 .thenReturn(metricsForPassword("abcdXYZ5"));
5921         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5922         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5923     }
5924 
5925     @Test
isActivePasswordSufficient_UnifiedWorkChallenge_ProfileComplexityRequirementMet()5926     public void isActivePasswordSufficient_UnifiedWorkChallenge_ProfileComplexityRequirementMet()
5927             throws Exception {
5928         // Create work profile with unified challenge
5929         final int managedProfileUserId = 15;
5930         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5931         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5932                 /* separateChallenge */ false);
5933 
5934         // Set profile password complexity requirement. No password added yet so
5935         // {profile, parent}.isActivePasswordSufficient should return false
5936         mContext.binder.callingUid = managedProfileAdminUid;
5937         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
5938         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5939         assertThat(parentDpm.isActivePasswordSufficient()).isFalse();
5940 
5941         // Set a device lockscreen and verify {profile, parent}.isActivePasswordSufficient is true
5942         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5943                 .thenReturn(metricsForPin("51567548"));
5944         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5945         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5946     }
5947 
5948     @Test
isActivePasswordSufficient_UnifiedWorkChallenge_ParentQualityRequirementMet()5949     public void isActivePasswordSufficient_UnifiedWorkChallenge_ParentQualityRequirementMet()
5950             throws Exception {
5951         assumeDeprecatedPasswordApisSupported();
5952 
5953         // Create work profile with unified challenge
5954         final int managedProfileUserId = 15;
5955         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5956         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5957                 /* separateChallenge */ false);
5958 
5959         // Set parent password quality requirement. No password added yet so
5960         // {profile, parent}.isActivePasswordSufficient should return false
5961         mContext.binder.callingUid = managedProfileAdminUid;
5962         parentDpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
5963         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5964         assertThat(parentDpm.isActivePasswordSufficient()).isFalse();
5965 
5966         // Set a device lockscreen and verify {profile, parent}.isActivePasswordSufficient is true
5967         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5968                 .thenReturn(metricsForPassword("abcdXYZ5"));
5969         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5970         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5971     }
5972 
5973     @Test
isActivePasswordSufficient_UnifiedWorkChallenge_ParentComplexityRequirementMet()5974     public void isActivePasswordSufficient_UnifiedWorkChallenge_ParentComplexityRequirementMet()
5975             throws Exception {
5976         // Create work profile with unified challenge
5977         final int managedProfileUserId = 15;
5978         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
5979         addManagedProfileForPasswordTests(managedProfileUserId, managedProfileAdminUid,
5980                 /* separateChallenge */ false);
5981 
5982         // Set parent password complexity requirement. No password added yet so
5983         // {profile, parent}.isActivePasswordSufficient should return false
5984         mContext.binder.callingUid = managedProfileAdminUid;
5985         parentDpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_MEDIUM);
5986         assertThat(dpm.isActivePasswordSufficient()).isFalse();
5987         assertThat(parentDpm.isActivePasswordSufficient()).isFalse();
5988 
5989         // Set a device lockscreen and verify {profile, parent}.isActivePasswordSufficient is true
5990         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
5991                 .thenReturn(metricsForPin("5156"));
5992         assertThat(dpm.isActivePasswordSufficient()).isTrue();
5993         assertThat(parentDpm.isActivePasswordSufficient()).isTrue();
5994     }
5995 
addManagedProfileForPasswordTests(int userId, int adminUid, boolean separateChallenge)5996     private void addManagedProfileForPasswordTests(int userId, int adminUid,
5997             boolean separateChallenge) throws Exception {
5998         addManagedProfile(admin1, adminUid, admin1);
5999         when(getServices().userManager.getProfileParent(userId))
6000                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
6001         doReturn(separateChallenge).when(getServices().lockPatternUtils)
6002                 .isSeparateProfileChallengeEnabled(userId);
6003         doReturn(!separateChallenge).when(getServices().lockPatternUtils)
6004                 .isProfileWithUnifiedChallenge(userId);
6005         when(getServices().userManager.getCredentialOwnerProfile(userId))
6006                 .thenReturn(separateChallenge ? userId : UserHandle.USER_SYSTEM);
6007         when(getServices().lockSettingsInternal.getUserPasswordMetrics(userId))
6008                 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
6009         when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
6010                 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
6011     }
6012 
6013     @Test
testPasswordQualityAppliesToParentPreS()6014     public void testPasswordQualityAppliesToParentPreS() throws Exception {
6015         assumeDeprecatedPasswordApisSupported();
6016 
6017         final int managedProfileUserId = CALLER_USER_HANDLE;
6018         final int managedProfileAdminUid =
6019                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
6020         mContext.binder.callingUid = managedProfileAdminUid;
6021         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
6022         when(getServices().userManager.getProfileParent(CALLER_USER_HANDLE))
6023                 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
6024 
6025         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
6026         assertThat(parentDpm.getPasswordQuality(null))
6027                 .isEqualTo(DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
6028     }
6029 
6030     @Test
testPasswordQualityDoesNotApplyToParentPostS()6031     public void testPasswordQualityDoesNotApplyToParentPostS() throws Exception {
6032         final int managedProfileUserId = CALLER_USER_HANDLE;
6033         final int managedProfileAdminUid =
6034                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
6035         mContext.binder.callingUid = managedProfileAdminUid;
6036         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
6037 
6038         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
6039         assertThat(parentDpm.getPasswordQuality(admin1))
6040                 .isEqualTo(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
6041     }
6042 
setActivePasswordState(PasswordMetrics passwordMetrics)6043     private void setActivePasswordState(PasswordMetrics passwordMetrics)
6044             throws Exception {
6045         final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
6046         final long ident = mContext.binder.clearCallingIdentity();
6047 
6048         when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
6049                 .thenReturn(passwordMetrics);
6050         dpm.reportPasswordChanged(passwordMetrics, userHandle);
6051 
6052         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
6053                 MockUtils.checkIntentAction(
6054                         DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
6055                 MockUtils.checkUserHandle(userHandle),
6056                 eq(null),
6057                 any(Bundle.class));
6058 
6059         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
6060         intent.setComponent(admin1);
6061         intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
6062 
6063         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
6064                 MockUtils.checkIntent(intent),
6065                 MockUtils.checkUserHandle(userHandle),
6066                 eq(null),
6067                 any());
6068 
6069         // CertificateMonitor.updateInstalledCertificates is called on the background thread,
6070         // let it finish with system uid, otherwise it will throw and crash.
6071         flushTasks(dpms);
6072 
6073         mContext.binder.restoreCallingIdentity(ident);
6074     }
6075 
6076     @Test
testIsCurrentInputMethodSetByOwnerForDeviceOwner()6077     public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
6078         final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
6079         final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
6080         final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
6081         final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
6082                 DpmMockContext.SYSTEM_UID);
6083         final int secondUserSystemUid = UserHandle.getUid(CALLER_USER_HANDLE,
6084                 DpmMockContext.SYSTEM_UID);
6085 
6086         // Set up a device owner.
6087         mContext.binder.callingUid = deviceOwnerUid;
6088         setupDeviceOwner();
6089 
6090         // First and second user set IMEs manually.
6091         mContext.binder.callingUid = firstUserSystemUid;
6092         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6093         mContext.binder.callingUid = secondUserSystemUid;
6094         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6095 
6096         // Device owner changes IME for first user.
6097         mContext.binder.callingUid = deviceOwnerUid;
6098         when(getServices().settings.settingsSecureGetStringForUser(currentIme,
6099                 UserHandle.USER_SYSTEM)).thenReturn("ime1");
6100         dpm.setSecureSetting(admin1, currentIme, "ime2");
6101         verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
6102                 UserHandle.USER_SYSTEM);
6103         reset(getServices().settings);
6104         dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
6105         mContext.binder.callingUid = firstUserSystemUid;
6106         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6107         mContext.binder.callingUid = secondUserSystemUid;
6108         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6109 
6110         // Second user changes IME manually.
6111         dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE);
6112         mContext.binder.callingUid = firstUserSystemUid;
6113         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6114         mContext.binder.callingUid = secondUserSystemUid;
6115         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6116 
6117         // First user changes IME manually.
6118         dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
6119         mContext.binder.callingUid = firstUserSystemUid;
6120         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6121         mContext.binder.callingUid = secondUserSystemUid;
6122         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6123 
6124         // Device owner changes IME for first user again.
6125         mContext.binder.callingUid = deviceOwnerUid;
6126         when(getServices().settings.settingsSecureGetStringForUser(currentIme,
6127                 UserHandle.USER_SYSTEM)).thenReturn("ime2");
6128         dpm.setSecureSetting(admin1, currentIme, "ime3");
6129         verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
6130                 UserHandle.USER_SYSTEM);
6131         dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
6132         mContext.binder.callingUid = firstUserSystemUid;
6133         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6134         mContext.binder.callingUid = secondUserSystemUid;
6135         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6136 
6137         // Restarting the DPMS should not lose information.
6138         initializeDpms();
6139         mContext.binder.callingUid = firstUserSystemUid;
6140         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6141         mContext.binder.callingUid = secondUserSystemUid;
6142         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6143 
6144         // Device owner can find out whether it set the current IME itself.
6145         mContext.binder.callingUid = deviceOwnerUid;
6146         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6147 
6148         // Removing the device owner should clear the information that it set the current IME.
6149         clearDeviceOwner();
6150         mContext.binder.callingUid = firstUserSystemUid;
6151         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6152         mContext.binder.callingUid = secondUserSystemUid;
6153         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6154     }
6155 
6156     @Test
testIsCurrentInputMethodSetByOwnerForProfileOwner()6157     public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
6158         final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
6159         final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
6160         final int profileOwnerUid = DpmMockContext.CALLER_UID;
6161         final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
6162                 DpmMockContext.SYSTEM_UID);
6163         final int secondUserSystemUid = UserHandle.getUid(CALLER_USER_HANDLE,
6164                 DpmMockContext.SYSTEM_UID);
6165 
6166         // Set up a profile owner.
6167         mContext.binder.callingUid = profileOwnerUid;
6168         setupProfileOwner();
6169 
6170         // First and second user set IMEs manually.
6171         mContext.binder.callingUid = firstUserSystemUid;
6172         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6173         mContext.binder.callingUid = secondUserSystemUid;
6174         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6175 
6176         // Profile owner changes IME for second user.
6177         mContext.binder.callingUid = profileOwnerUid;
6178         when(getServices().settings.settingsSecureGetStringForUser(currentIme,
6179                 CALLER_USER_HANDLE)).thenReturn("ime1");
6180         dpm.setSecureSetting(admin1, currentIme, "ime2");
6181         verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
6182                 CALLER_USER_HANDLE);
6183         reset(getServices().settings);
6184         dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE);
6185         mContext.binder.callingUid = firstUserSystemUid;
6186         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6187         mContext.binder.callingUid = secondUserSystemUid;
6188         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6189 
6190         // First user changes IME manually.
6191         dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
6192         mContext.binder.callingUid = firstUserSystemUid;
6193         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6194         mContext.binder.callingUid = secondUserSystemUid;
6195         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6196 
6197         // Second user changes IME manually.
6198         dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE);
6199         mContext.binder.callingUid = firstUserSystemUid;
6200         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6201         mContext.binder.callingUid = secondUserSystemUid;
6202         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6203 
6204         // Profile owner changes IME for second user again.
6205         mContext.binder.callingUid = profileOwnerUid;
6206         when(getServices().settings.settingsSecureGetStringForUser(currentIme,
6207                 CALLER_USER_HANDLE)).thenReturn("ime2");
6208         dpm.setSecureSetting(admin1, currentIme, "ime3");
6209         verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
6210                 CALLER_USER_HANDLE);
6211         dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE);
6212         mContext.binder.callingUid = firstUserSystemUid;
6213         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6214         mContext.binder.callingUid = secondUserSystemUid;
6215         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6216 
6217         // Restarting the DPMS should not lose information.
6218         initializeDpms();
6219         mContext.binder.callingUid = firstUserSystemUid;
6220         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6221         mContext.binder.callingUid = secondUserSystemUid;
6222         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6223 
6224         // Profile owner can find out whether it set the current IME itself.
6225         mContext.binder.callingUid = profileOwnerUid;
6226         assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue();
6227 
6228         // Removing the profile owner should clear the information that it set the current IME.
6229         dpm.clearProfileOwner(admin1);
6230         mContext.binder.callingUid = firstUserSystemUid;
6231         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6232         mContext.binder.callingUid = secondUserSystemUid;
6233         assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse();
6234     }
6235 
6236     @Test
testSetPermittedCrossProfileNotificationListeners_unavailableForDo()6237     public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
6238             throws Exception {
6239         // Set up a device owner.
6240         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
6241         setupDeviceOwner();
6242         assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
6243     }
6244 
6245     @Test
testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()6246     public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
6247             throws Exception {
6248         // Set up a profile owner.
6249         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
6250         setupProfileOwner();
6251         assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
6252     }
6253 
assertSetPermittedCrossProfileNotificationListenersUnavailable( int adminUid)6254     private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
6255             int adminUid) throws Exception {
6256         mContext.binder.callingUid = adminUid;
6257         final int userId = UserHandle.getUserId(adminUid);
6258 
6259         final String packageName = "some.package";
6260         assertThat(dpms.setPermittedCrossProfileNotificationListeners(
6261         admin1, Collections.singletonList(packageName))).isFalse();
6262         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull();
6263 
6264         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6265         assertThat(dpms.isNotificationListenerServicePermitted(packageName, userId)).isTrue();
6266 
6267         // Attempt to set to empty list (which means no listener is allowlisted)
6268         mContext.binder.callingUid = adminUid;
6269         assertThat(dpms.setPermittedCrossProfileNotificationListeners(
6270                 admin1, emptyList())).isFalse();
6271         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull();
6272 
6273         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6274         assertThat(dpms.isNotificationListenerServicePermitted(packageName, userId)).isTrue();
6275     }
6276 
6277     @Test
testIsNotificationListenerServicePermitted_onlySystemCanCall()6278     public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
6279         // Set up a managed profile
6280         final int MANAGED_PROFILE_USER_ID = 15;
6281         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
6282         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
6283         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6284 
6285         final String permittedListener = "some.package";
6286         setupPackageInPackageManager(
6287                 permittedListener,
6288                 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
6289                 /*appId=*/ 12345, /*flags=*/ 0);
6290 
6291         assertThat(dpms.setPermittedCrossProfileNotificationListeners(
6292         admin1, Collections.singletonList(permittedListener))).isTrue();
6293 
6294         // isNotificationListenerServicePermitted should throw if not called from System.
6295         assertExpectException(SecurityException.class, /* messageRegex= */ null,
6296                 () -> dpms.isNotificationListenerServicePermitted(
6297                         permittedListener, MANAGED_PROFILE_USER_ID));
6298 
6299         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6300         assertThat(dpms.isNotificationListenerServicePermitted(
6301         permittedListener, MANAGED_PROFILE_USER_ID)).isTrue();
6302     }
6303 
6304     @Test
testSetPermittedCrossProfileNotificationListeners_managedProfile()6305     public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
6306             throws Exception {
6307         // Set up a managed profile
6308         final int MANAGED_PROFILE_USER_ID = 15;
6309         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
6310         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
6311         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6312 
6313         final String permittedListener = "permitted.package";
6314         int appId = 12345;
6315         setupPackageInPackageManager(
6316                 permittedListener,
6317                 UserHandle.USER_SYSTEM,  // We check the packageInfo from the primary user.
6318                 appId, /*flags=*/ 0);
6319 
6320         final String notPermittedListener = "not.permitted.package";
6321         setupPackageInPackageManager(
6322                 notPermittedListener,
6323                 UserHandle.USER_SYSTEM,  // We check the packageInfo from the primary user.
6324                 ++appId, /*flags=*/ 0);
6325 
6326         final String systemListener = "system.package";
6327         setupPackageInPackageManager(
6328                 systemListener,
6329                 UserHandle.USER_SYSTEM,  // We check the packageInfo from the primary user.
6330                 ++appId, ApplicationInfo.FLAG_SYSTEM);
6331 
6332         // By default all packages are allowed
6333         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull();
6334 
6335         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6336         assertThat(dpms.isNotificationListenerServicePermitted(
6337         permittedListener, MANAGED_PROFILE_USER_ID)).isTrue();
6338         assertThat(dpms.isNotificationListenerServicePermitted(
6339         notPermittedListener, MANAGED_PROFILE_USER_ID)).isTrue();
6340         assertThat(dpms.isNotificationListenerServicePermitted(
6341         systemListener, MANAGED_PROFILE_USER_ID)).isTrue();
6342 
6343         // Setting only one package in the allowlist
6344         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6345         assertThat(dpms.setPermittedCrossProfileNotificationListeners(
6346         admin1, Collections.singletonList(permittedListener))).isTrue();
6347         final List<String> permittedListeners =
6348                 dpms.getPermittedCrossProfileNotificationListeners(admin1);
6349         assertThat(permittedListeners.size()).isEqualTo(1);
6350         assertThat(permittedListeners.get(0)).isEqualTo(permittedListener);
6351 
6352         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6353         assertThat(dpms.isNotificationListenerServicePermitted(
6354         permittedListener, MANAGED_PROFILE_USER_ID)).isTrue();
6355         assertThat(dpms.isNotificationListenerServicePermitted(
6356         notPermittedListener, MANAGED_PROFILE_USER_ID)).isFalse();
6357         // System packages are always allowed (even if not in the allowlist)
6358         assertThat(dpms.isNotificationListenerServicePermitted(
6359         systemListener, MANAGED_PROFILE_USER_ID)).isTrue();
6360 
6361         // Setting an empty allowlist - only system listeners allowed
6362         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6363         assertThat(dpms.setPermittedCrossProfileNotificationListeners(
6364                 admin1, emptyList())).isTrue();
6365         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1).size()).isEqualTo(0);
6366 
6367         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6368         assertThat(dpms.isNotificationListenerServicePermitted(
6369         permittedListener, MANAGED_PROFILE_USER_ID)).isFalse();
6370         assertThat(dpms.isNotificationListenerServicePermitted(
6371         notPermittedListener, MANAGED_PROFILE_USER_ID)).isFalse();
6372         // System packages are always allowed (even if not in the allowlist)
6373         assertThat(dpms.isNotificationListenerServicePermitted(
6374         systemListener, MANAGED_PROFILE_USER_ID)).isTrue();
6375 
6376         // Setting a null allowlist - all listeners allowed
6377         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6378         assertThat(dpms.setPermittedCrossProfileNotificationListeners(admin1, null)).isTrue();
6379         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull();
6380 
6381         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6382         assertThat(dpms.isNotificationListenerServicePermitted(
6383         permittedListener, MANAGED_PROFILE_USER_ID)).isTrue();
6384         assertThat(dpms.isNotificationListenerServicePermitted(
6385         notPermittedListener, MANAGED_PROFILE_USER_ID)).isTrue();
6386         assertThat(dpms.isNotificationListenerServicePermitted(
6387         systemListener, MANAGED_PROFILE_USER_ID)).isTrue();
6388     }
6389 
6390     @Test
testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()6391     public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
6392             throws Exception {
6393         // Set up a managed profile
6394         final int MANAGED_PROFILE_USER_ID = 15;
6395         final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
6396         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
6397         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6398 
6399         final String nonSystemPackage = "non.system.package";
6400         int appId = 12345;
6401         setupPackageInPackageManager(
6402                 nonSystemPackage,
6403                 UserHandle.USER_SYSTEM,  // We check the packageInfo from the primary user.
6404                 appId, /*flags=*/ 0);
6405 
6406         final String systemListener = "system.package";
6407         setupPackageInPackageManager(
6408                 systemListener,
6409                 UserHandle.USER_SYSTEM,  // We check the packageInfo from the primary user.
6410                 ++appId, ApplicationInfo.FLAG_SYSTEM);
6411 
6412         // By default all packages are allowed (for all profiles)
6413         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull();
6414 
6415         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6416         assertThat(dpms.isNotificationListenerServicePermitted(
6417                 nonSystemPackage, MANAGED_PROFILE_USER_ID)).isTrue();
6418         assertThat(dpms.isNotificationListenerServicePermitted(
6419                 systemListener, MANAGED_PROFILE_USER_ID)).isTrue();
6420         assertThat(dpms.isNotificationListenerServicePermitted(
6421                 nonSystemPackage, UserHandle.USER_SYSTEM)).isTrue();
6422         assertThat(dpms.isNotificationListenerServicePermitted(
6423                 systemListener, UserHandle.USER_SYSTEM)).isTrue();
6424 
6425         // Setting an empty allowlist - only system listeners allowed in managed profile, but
6426         // all allowed in primary profile
6427         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
6428         assertThat(dpms.setPermittedCrossProfileNotificationListeners(
6429                 admin1, emptyList())).isTrue();
6430         assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1).size()).isEqualTo(0);
6431 
6432         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6433         assertThat(dpms.isNotificationListenerServicePermitted(
6434                 nonSystemPackage, MANAGED_PROFILE_USER_ID)).isFalse();
6435         assertThat(dpms.isNotificationListenerServicePermitted(
6436                 systemListener, MANAGED_PROFILE_USER_ID)).isTrue();
6437         assertThat(dpms.isNotificationListenerServicePermitted(
6438                 nonSystemPackage, UserHandle.USER_SYSTEM)).isTrue();
6439         assertThat(dpms.isNotificationListenerServicePermitted(
6440                 systemListener, UserHandle.USER_SYSTEM)).isTrue();
6441     }
6442 
6443     @Test
testGetOwnerInstalledCaCertsForDeviceOwner()6444     public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
6445         mServiceContext.packageName = mRealTestContext.getPackageName();
6446         mServiceContext.applicationInfo = new ApplicationInfo();
6447         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6448         mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
6449         setDeviceOwner();
6450 
6451         verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
6452     }
6453 
6454     @Test
testGetOwnerInstalledCaCertsForProfileOwner()6455     public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
6456         mServiceContext.packageName = mRealTestContext.getPackageName();
6457         mServiceContext.applicationInfo = new ApplicationInfo();
6458         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6459         mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
6460         setAsProfileOwner(admin1);
6461 
6462         verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
6463         verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
6464     }
6465 
6466     @Test
testGetOwnerInstalledCaCertsForDelegate()6467     public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
6468         mServiceContext.packageName = mRealTestContext.getPackageName();
6469         mServiceContext.applicationInfo = new ApplicationInfo();
6470         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6471         mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
6472         setAsProfileOwner(admin1);
6473 
6474         var caller = new DpmMockContext(getServices(), mRealTestContext);
6475         caller.packageName = "com.example.delegate";
6476         caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
6477                 CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
6478 
6479         // Make caller a delegated cert installer.
6480         runAsCaller(mAdmin1Context, dpms,
6481                 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
6482 
6483         verifyCanGetOwnerInstalledCaCerts(null, caller);
6484         verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
6485     }
6486 
6487     @Test
testDisallowSharingIntoProfileSetRestriction()6488     public void testDisallowSharingIntoProfileSetRestriction() {
6489         when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
6490                 .thenReturn("com.android.managedprovisioning");
6491         when(getServices().userManagerInternal.getProfileParentId(anyInt()))
6492                 .thenReturn(UserHandle.USER_SYSTEM);
6493         mServiceContext.binder.callingPid = DpmMockContext.SYSTEM_PID;
6494         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6495         Bundle restriction = new Bundle();
6496         restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
6497 
6498         RestrictionsListener listener = new RestrictionsListener(
6499                 mServiceContext, getServices().userManagerInternal, dpms);
6500         listener.onUserRestrictionsChanged(CALLER_USER_HANDLE, restriction, new Bundle());
6501 
6502         verifyDataSharingAppliedBroadcast();
6503     }
6504 
6505     @Test
testDisallowSharingIntoProfileClearRestriction()6506     public void testDisallowSharingIntoProfileClearRestriction() {
6507         when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
6508                 .thenReturn("com.android.managedprovisioning");
6509         when(getServices().userManagerInternal.getProfileParentId(anyInt()))
6510                 .thenReturn(UserHandle.USER_SYSTEM);
6511         mServiceContext.binder.callingPid = DpmMockContext.SYSTEM_PID;
6512         mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6513         Bundle restriction = new Bundle();
6514         restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
6515 
6516         RestrictionsListener listener = new RestrictionsListener(
6517                 mServiceContext, getServices().userManagerInternal, dpms);
6518         listener.onUserRestrictionsChanged(CALLER_USER_HANDLE, new Bundle(), restriction);
6519 
6520         verifyDataSharingAppliedBroadcast();
6521     }
6522 
6523     @Test
testDisallowSharingIntoProfileUnchanged()6524     public void testDisallowSharingIntoProfileUnchanged() {
6525         RestrictionsListener listener = new RestrictionsListener(
6526                 mContext, getServices().userManagerInternal, dpms);
6527         listener.onUserRestrictionsChanged(CALLER_USER_HANDLE, new Bundle(), new Bundle());
6528         verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
6529     }
6530 
verifyDataSharingAppliedBroadcast()6531     private void verifyDataSharingAppliedBroadcast() {
6532         Intent expectedIntent = new Intent(
6533                 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED);
6534         verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
6535                 MockUtils.checkIntent(expectedIntent),
6536                 MockUtils.checkUserHandle(CALLER_USER_HANDLE));
6537     }
6538 
6539     @Test
testOverrideApnAPIsFailWithPO()6540     public void testOverrideApnAPIsFailWithPO() throws Exception {
6541         when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY))
6542                 .thenReturn(true);
6543         // FEATURE_TELEPHONY is set in DPMS's constructor and therefore a new DPMS instance
6544         // is created after turning on the feature.
6545         initializeDpms();
6546         setupProfileOwner();
6547         ApnSetting apn = (new ApnSetting.Builder())
6548             .setApnName("test")
6549             .setEntryName("test")
6550             .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
6551             .build();
6552         assertExpectException(SecurityException.class, null, () ->
6553                 dpm.addOverrideApn(admin1, apn));
6554         assertExpectException(SecurityException.class, null, () ->
6555                 dpm.updateOverrideApn(admin1, 0, apn));
6556         assertExpectException(SecurityException.class, null, () ->
6557                 dpm.removeOverrideApn(admin1, 0));
6558         assertExpectException(SecurityException.class, null, () ->
6559                 dpm.getOverrideApns(admin1));
6560         assertExpectException(SecurityException.class, null, () ->
6561                 dpm.setOverrideApnsEnabled(admin1, false));
6562         assertExpectException(SecurityException.class, null, () ->
6563                 dpm.isOverrideApnEnabled(admin1));
6564     }
6565 
verifyCanGetOwnerInstalledCaCerts( final ComponentName caller, final DpmMockContext callerContext)6566     private void verifyCanGetOwnerInstalledCaCerts(
6567             final ComponentName caller, final DpmMockContext callerContext) throws Exception {
6568         final String alias = "cert";
6569         final byte[] caCert = TEST_CA.getBytes();
6570 
6571         // device admin (used for posting the tls notification)
6572         DpmMockContext admin1Context = mAdmin1Context;
6573         if (admin1.getPackageName().equals(callerContext.getPackageName())) {
6574             admin1Context = callerContext;
6575         }
6576         when(admin1Context.resources.getColor(anyInt(), any())).thenReturn(Color.WHITE);
6577 
6578         // caller: device admin or delegated certificate installer
6579         callerContext.applicationInfo = new ApplicationInfo();
6580         final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
6581 
6582         // system_server
6583         final DpmMockContext serviceContext = mContext;
6584         serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6585         getServices().addPackageContext(callerUser, admin1Context);
6586         getServices().addPackageContext(callerUser, callerContext);
6587 
6588         // Install a CA cert.
6589         runAsCaller(callerContext, dpms, (dpm) -> {
6590             when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
6591                         .thenReturn(alias);
6592             assertThat(dpm.installCaCert(caller, caCert)).isTrue();
6593             when(getServices().keyChainConnection.getService().getUserCaAliases())
6594                     .thenReturn(asSlice(new String[] {alias}));
6595         });
6596 
6597         getServices().injectBroadcast(mServiceContext,
6598                 new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
6599                         .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
6600                 callerUser.getIdentifier());
6601         flushTasks(dpms);
6602 
6603         final List<String> ownerInstalledCaCerts = new ArrayList<>();
6604 
6605         // Device Owner / Profile Owner can find out which CA certs were installed by itself.
6606         runAsCaller(admin1Context, dpms, (dpm) -> {
6607             final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
6608             assertThat(installedCaCerts).isEqualTo(Collections.singletonList(alias));
6609             ownerInstalledCaCerts.addAll(installedCaCerts);
6610         });
6611 
6612         // Restarting the DPMS should not lose information.
6613         initializeDpms();
6614         runAsCaller(admin1Context, dpms,
6615                 (dpm) -> assertThat(dpm.getOwnerInstalledCaCerts(callerUser))
6616                         .isEqualTo(ownerInstalledCaCerts));
6617 
6618         // System can find out which CA certs were installed by the Device Owner / Profile Owner.
6619         runAsCaller(serviceContext, dpms, (dpm) -> {
6620             assertThat(dpm.getOwnerInstalledCaCerts(callerUser)).isEqualTo(ownerInstalledCaCerts);
6621 
6622             // Remove the CA cert.
6623             reset(getServices().keyChainConnection.getService());
6624         });
6625 
6626         getServices().injectBroadcast(mServiceContext,
6627                 new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
6628                         .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
6629                 callerUser.getIdentifier());
6630         flushTasks(dpms);
6631 
6632         // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
6633         // Owner.
6634         runAsCaller(admin1Context, dpms, (dpm) -> {
6635             MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
6636         });
6637     }
6638 
verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval( final ComponentName callerName, final DpmMockContext callerContext)6639     private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
6640             final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
6641         final String alias = "cert";
6642         final byte[] caCert = TEST_CA.getBytes();
6643 
6644         // device admin (used for posting the tls notification)
6645         DpmMockContext admin1Context = mAdmin1Context;
6646         if (admin1.getPackageName().equals(callerContext.getPackageName())) {
6647             admin1Context = callerContext;
6648         }
6649         when(admin1Context.resources.getColor(anyInt(), any())).thenReturn(Color.WHITE);
6650 
6651         // caller: device admin or delegated certificate installer
6652         callerContext.applicationInfo = new ApplicationInfo();
6653         final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
6654 
6655         // system_server
6656         final DpmMockContext serviceContext = mContext;
6657         serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6658         getServices().addPackageContext(callerUser, admin1Context);
6659         getServices().addPackageContext(callerUser, callerContext);
6660 
6661         // Install a CA cert as caller
6662         runAsCaller(callerContext, dpms, (dpm) -> {
6663             when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
6664                     .thenReturn(alias);
6665             assertThat(dpm.installCaCert(callerName, caCert)).isTrue();
6666         });
6667 
6668         // Fake the CA cert as having been installed
6669         when(getServices().keyChainConnection.getService().getUserCaAliases())
6670                 .thenReturn(asSlice(new String[] {alias}));
6671         getServices().injectBroadcast(mServiceContext,
6672                 new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
6673                         .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
6674                 callerUser.getIdentifier());
6675         flushTasks(dpms);
6676 
6677         // Removing the Profile Owner should clear the information on which CA certs were installed
6678         runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
6679 
6680         runAsCaller(serviceContext, dpms, (dpm) -> {
6681             final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
6682             assertThat(ownerInstalledCaCerts).isNotNull();
6683             assertThat(ownerInstalledCaCerts.isEmpty()).isTrue();
6684         });
6685     }
6686 
verifyRebootWipeUserData(boolean wipeEuicc)6687     private void verifyRebootWipeUserData(boolean wipeEuicc) throws Exception {
6688         verify(getServices().recoverySystem).rebootWipeUserData(/*shutdown=*/ eq(false),
6689                 /* reason= */ anyString(), /*force=*/ eq(true), eq(wipeEuicc),
6690                 /* wipeAdoptableStorage= */ eq(false), /* wipeFactoryResetProtection= */ eq(false));
6691     }
6692 
assertAttestationFlags(int attestationFlags, int[] expectedFlags)6693     private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
6694         int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
6695         Arrays.sort(gotFlags);
6696         Arrays.sort(expectedFlags);
6697         assertThat(Arrays.equals(expectedFlags, gotFlags)).isTrue();
6698     }
6699 
6700     @Test
testTranslationOfIdAttestationFlag()6701     public void testTranslationOfIdAttestationFlag() {
6702         int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
6703         int[] correspondingAttUtilsTypes = new int[]{
6704             AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
6705             AttestationUtils.ID_TYPE_MEID};
6706 
6707         // Test translation of zero flags
6708         assertThat(DevicePolicyManagerService.translateIdAttestationFlags(0)).isNull();
6709 
6710         // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
6711         // non-null array
6712         assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
6713 
6714         // Test translation of a single flag
6715         assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
6716                 new int[] {AttestationUtils.ID_TYPE_SERIAL});
6717         assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
6718 
6719         // Test translation of two flags
6720         assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
6721                 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
6722         assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
6723                 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
6724 
6725         // Test translation of all three flags
6726         assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
6727                 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
6728                     AttestationUtils.ID_TYPE_MEID});
6729         // Test translation of all three flags
6730         assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
6731                 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
6732                     AttestationUtils.ID_TYPE_MEID});
6733     }
6734 
6735     @Test
testRevertDeviceOwnership_noMetadataFile()6736     public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
6737         setDeviceOwner();
6738         initializeDpms();
6739         assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse();
6740         assertThat(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue();
6741         assertThat(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM)).isTrue();
6742     }
6743 
6744     @FlakyTest(bugId = 148934649)
6745     @Test
testRevertDeviceOwnership_adminAndDeviceMigrated()6746     public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
6747         DpmTestUtils.writeInputStreamToFile(
6748                 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
6749                 getDeviceOwnerPoliciesFile());
6750         DpmTestUtils.writeInputStreamToFile(
6751                 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
6752                 getDeviceOwnerFile());
6753         assertDeviceOwnershipRevertedWithFakeTransferMetadata();
6754     }
6755 
6756     @FlakyTest(bugId = 148934649)
6757     @Test
testRevertDeviceOwnership_deviceNotMigrated()6758     public void testRevertDeviceOwnership_deviceNotMigrated() throws Exception {
6759         DpmTestUtils.writeInputStreamToFile(
6760                 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
6761                 getDeviceOwnerPoliciesFile());
6762         DpmTestUtils.writeInputStreamToFile(
6763                 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
6764                 getDeviceOwnerFile());
6765         assertDeviceOwnershipRevertedWithFakeTransferMetadata();
6766     }
6767 
6768     @Test
testRevertDeviceOwnership_adminAndDeviceNotMigrated()6769     public void testRevertDeviceOwnership_adminAndDeviceNotMigrated() throws Exception {
6770         DpmTestUtils.writeInputStreamToFile(
6771                 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
6772                 getDeviceOwnerPoliciesFile());
6773         DpmTestUtils.writeInputStreamToFile(
6774                 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
6775                 getDeviceOwnerFile());
6776         assertDeviceOwnershipRevertedWithFakeTransferMetadata();
6777     }
6778 
6779     @Test
testRevertProfileOwnership_noMetadataFile()6780     public void testRevertProfileOwnership_noMetadataFile() throws Exception {
6781         setupProfileOwner();
6782         initializeDpms();
6783         assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse();
6784         assertThat(dpms.isProfileOwner(admin1, CALLER_USER_HANDLE)).isTrue();
6785         assertThat(dpms.isAdminActive(admin1, CALLER_USER_HANDLE)).isTrue();
6786     }
6787 
6788     @FlakyTest(bugId = 148934649)
6789     @Test
testRevertProfileOwnership_adminAndProfileMigrated()6790     public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
6791         getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
6792                 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
6793         DpmTestUtils.writeInputStreamToFile(
6794                 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
6795                 getProfileOwnerPoliciesFile());
6796         DpmTestUtils.writeInputStreamToFile(
6797                 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
6798                 getProfileOwnerFile());
6799         assertProfileOwnershipRevertedWithFakeTransferMetadata();
6800     }
6801 
6802     @FlakyTest(bugId = 148934649)
6803     @Test
testRevertProfileOwnership_profileNotMigrated()6804     public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
6805         getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
6806                 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
6807         DpmTestUtils.writeInputStreamToFile(
6808                 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
6809                 getProfileOwnerPoliciesFile());
6810         DpmTestUtils.writeInputStreamToFile(
6811                 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
6812                 getProfileOwnerFile());
6813         assertProfileOwnershipRevertedWithFakeTransferMetadata();
6814     }
6815 
6816     @Test
testRevertProfileOwnership_adminAndProfileNotMigrated()6817     public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
6818         getServices().addUser(CALLER_USER_HANDLE, 0,
6819                 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
6820         DpmTestUtils.writeInputStreamToFile(
6821                 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
6822                 getProfileOwnerPoliciesFile());
6823         DpmTestUtils.writeInputStreamToFile(
6824                 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
6825                 getProfileOwnerFile());
6826         assertProfileOwnershipRevertedWithFakeTransferMetadata();
6827     }
6828 
6829     @Test
testGrantDeviceIdsAccess_notToProfileOwner()6830     public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
6831         setupProfileOwner();
6832         configureContextForAccess(mContext, false);
6833 
6834         assertExpectException(SecurityException.class, /* messageRegex= */ null,
6835                 () -> dpm.setProfileOwnerOnOrganizationOwnedDevice(admin2, true));
6836     }
6837 
6838     @Test
testGrantDeviceIdsAccess_notByAuthorizedCaller()6839     public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
6840         setupProfileOwner();
6841         configureContextForAccess(mContext, false);
6842 
6843         assertExpectException(SecurityException.class, /* messageRegex= */ null,
6844                 () -> dpm.setProfileOwnerOnOrganizationOwnedDevice(admin1, true));
6845     }
6846 
6847     @Test
testGrantDeviceIdsAccess_byAuthorizedSystemCaller()6848     public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
6849         setupProfileOwner();
6850 
6851         // This method will throw if the system context could not call
6852         // markProfileOwnerOfOrganizationOwnedDevice successfully.
6853         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
6854     }
6855 
configureContextForAccess(DpmMockContext context, boolean granted)6856     private void configureContextForAccess(DpmMockContext context, boolean granted) {
6857         when(context.spiedContext.checkCallingPermission(
6858                 permission.MARK_DEVICE_ORGANIZATION_OWNED))
6859                 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
6860                         : PackageManager.PERMISSION_DENIED);
6861 
6862         when(getServices().userManager.getProfileParent(any()))
6863                 .thenReturn(UserHandle.SYSTEM);
6864     }
6865 
6866     @Test
testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning()6867     public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
6868         setupProfileOwner();
6869 
6870         final long ident = mServiceContext.binder.clearCallingIdentity();
6871         configureContextForAccess(mServiceContext, true);
6872         mServiceContext.permissions.add(permission.MARK_DEVICE_ORGANIZATION_OWNED);
6873 
6874         mServiceContext.binder.callingUid =
6875                 UserHandle.getUid(CALLER_USER_HANDLE,
6876                         DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
6877         try {
6878             runAsCaller(mServiceContext, dpms, dpm -> {
6879                 dpm.setProfileOwnerOnOrganizationOwnedDevice(admin1, true);
6880             });
6881         } finally {
6882             mServiceContext.binder.restoreCallingIdentity(ident);
6883         }
6884     }
6885 
6886     @Test
testHasDeviceIdAccessUnchecked_deviceOwnerCaller()6887     public void testHasDeviceIdAccessUnchecked_deviceOwnerCaller()
6888             throws Exception {
6889         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
6890         setupDeviceOwner();
6891         configureContextForAccess(mContext, false);
6892 
6893         // Device owner should be allowed to request Device ID attestation.
6894         assertThat(dpms.hasDeviceIdAccessUnchecked(
6895                 admin1.getPackageName(),
6896                 DpmMockContext.CALLER_SYSTEM_USER_UID)).isTrue();
6897 
6898         // Another package must not be allowed to request Device ID attestation.
6899         assertThat(dpms.hasDeviceIdAccessUnchecked(
6900                 DpmMockContext.ANOTHER_PACKAGE_NAME,
6901                 DpmMockContext.CALLER_SYSTEM_USER_UID)).isFalse();
6902     }
6903 
6904     @Test
testHasDeviceIdAccessUnchecked_profileOwnerCaller()6905     public void testHasDeviceIdAccessUnchecked_profileOwnerCaller()
6906             throws Exception {
6907         configureContextForAccess(mContext, false);
6908 
6909         // Make sure a security exception is thrown if the device has no profile owner.
6910         assertThat(dpms.hasDeviceIdAccessUnchecked(
6911                 admin1.getPackageName(),
6912                 DpmMockContext.CALLER_UID)).isFalse();
6913 
6914         setupProfileOwner();
6915         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
6916 
6917         // The profile owner is allowed to request Device ID attestation.
6918         assertThat(dpms.hasDeviceIdAccessUnchecked(
6919                 admin1.getPackageName(),
6920                 DpmMockContext.CALLER_UID)).isTrue();
6921 
6922         // But not another package.
6923         assertThat(dpms.hasDeviceIdAccessUnchecked(
6924                 DpmMockContext.ANOTHER_PACKAGE_NAME,
6925                 DpmMockContext.CALLER_UID)).isFalse();
6926 
6927         // Or another component which is not the admin.
6928         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
6929         assertThat(dpms.hasDeviceIdAccessUnchecked(
6930                 admin1.getPackageName(),
6931                 DpmMockContext.ANOTHER_UID)).isFalse();
6932     }
6933 
runAsDelegatedCertInstaller(DpmRunnable action)6934     public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
6935         final long ident = mServiceContext.binder.clearCallingIdentity();
6936 
6937         mServiceContext.binder.callingUid = UserHandle.getUid(CALLER_USER_HANDLE,
6938                 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
6939         try {
6940             runAsCaller(mServiceContext, dpms, action);
6941         } finally {
6942             mServiceContext.binder.restoreCallingIdentity(ident);
6943         }
6944     }
6945 
6946     @Test
testHasDeviceIdAccessUnchecked_delegateCaller()6947     public void testHasDeviceIdAccessUnchecked_delegateCaller() throws Exception {
6948         setupProfileOwner();
6949         markDelegatedCertInstallerAsInstalled();
6950 
6951         // Configure a delegated cert installer.
6952         runAsCaller(mServiceContext, dpms,
6953                 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
6954                         Arrays.asList(DELEGATION_CERT_INSTALL)));
6955 
6956         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
6957 
6958         // Make sure that the profile owner can still request Device ID attestation.
6959         assertThat(dpms.hasDeviceIdAccessUnchecked(
6960                 admin1.getPackageName(),
6961                 DpmMockContext.CALLER_UID)).isTrue();
6962 
6963         runAsDelegatedCertInstaller(dpm -> assertThat(
6964                 dpms.hasDeviceIdAccessUnchecked(
6965                         DpmMockContext.DELEGATE_PACKAGE_NAME,
6966                         UserHandle.getUid(CALLER_USER_HANDLE,
6967                                 DpmMockContext.DELEGATE_CERT_INSTALLER_UID))).isTrue());
6968     }
6969 
6970     @Test
testHasDeviceIdAccessUnchecked_delegateCallerWithoutPermissions()6971     public void testHasDeviceIdAccessUnchecked_delegateCallerWithoutPermissions()
6972             throws Exception {
6973         setupProfileOwner();
6974         markDelegatedCertInstallerAsInstalled();
6975 
6976         // Configure a delegated cert installer.
6977         runAsCaller(mServiceContext, dpms,
6978                 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
6979                         Arrays.asList(DELEGATION_CERT_INSTALL)));
6980 
6981         assertThat(dpms.hasDeviceIdAccessUnchecked(
6982                 admin1.getPackageName(),
6983                 DpmMockContext.CALLER_UID)).isFalse();
6984 
6985         runAsDelegatedCertInstaller(dpm -> {
6986             assertThat(dpms.hasDeviceIdAccessUnchecked(
6987                     DpmMockContext.DELEGATE_PACKAGE_NAME,
6988                     DpmMockContext.CALLER_UID)).isFalse();
6989         });
6990     }
6991 
6992     @Test
testGetPasswordComplexity_securityExceptionNotThrownForParentInstance()6993     public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
6994         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
6995         when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
6996                 new String[0]);
6997         mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
6998         setAsProfileOwner(admin1);
6999 
7000         parentDpm.getPasswordComplexity();
7001 
7002         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE);
7003     }
7004 
7005     @Test
testGetPasswordComplexity_illegalStateExceptionIfLocked()7006     public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
7007         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7008         when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
7009                 new String[0]);
7010         when(getServices().userManager.isUserUnlocked(CALLER_USER_HANDLE)).thenReturn(false);
7011         assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
7012     }
7013 
7014     @Test
testGetPasswordComplexity_securityExceptionWithoutPermissions()7015     public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
7016         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7017         when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
7018                 new String[0]);
7019         when(getServices().userManager.isUserUnlocked(CALLER_USER_HANDLE)).thenReturn(true);
7020         assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
7021     }
7022 
7023 
7024     @Test
testGetPasswordComplexity_currentUserNoPassword()7025     public void testGetPasswordComplexity_currentUserNoPassword() {
7026         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7027         when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
7028                 new String[0]);
7029         when(getServices().userManager.isUserUnlocked(CALLER_USER_HANDLE)).thenReturn(true);
7030         mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
7031         when(getServices().userManager.getCredentialOwnerProfile(CALLER_USER_HANDLE))
7032                 .thenReturn(CALLER_USER_HANDLE);
7033 
7034         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE);
7035     }
7036 
7037     @Test
testGetPasswordComplexity_currentUserHasPassword()7038     public void testGetPasswordComplexity_currentUserHasPassword() {
7039         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7040         when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
7041                 new String[0]);
7042         when(getServices().userManager.isUserUnlocked(CALLER_USER_HANDLE)).thenReturn(true);
7043         mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
7044         when(getServices().userManager.getCredentialOwnerProfile(CALLER_USER_HANDLE))
7045                 .thenReturn(CALLER_USER_HANDLE);
7046         when(getServices().lockSettingsInternal
7047                 .getUserPasswordMetrics(CALLER_USER_HANDLE))
7048                 .thenReturn(metricsForPassword("asdf"));
7049 
7050         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_MEDIUM);
7051     }
7052 
7053     @Test
testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword()7054     public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
7055         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7056         when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
7057                 new String[0]);
7058         when(getServices().userManager.isUserUnlocked(CALLER_USER_HANDLE)).thenReturn(true);
7059         mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
7060 
7061         UserInfo parentUser = new UserInfo();
7062         parentUser.id = CALLER_USER_HANDLE + 10;
7063         when(getServices().userManager.getCredentialOwnerProfile(CALLER_USER_HANDLE))
7064                 .thenReturn(parentUser.id);
7065 
7066         when(getServices().lockSettingsInternal
7067                 .getUserPasswordMetrics(CALLER_USER_HANDLE))
7068                 .thenReturn(metricsForPassword("asdf"));
7069         when(getServices().lockSettingsInternal
7070                 .getUserPasswordMetrics(parentUser.id))
7071                 .thenReturn(metricsForPassword("parentUser"));
7072 
7073         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_HIGH);
7074     }
7075 
7076     @Test
testCrossProfileCalendarPackages_initiallyEmpty()7077     public void testCrossProfileCalendarPackages_initiallyEmpty() {
7078         setAsProfileOwner(admin1);
7079         final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
7080         assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
7081     }
7082 
7083     @Test
testCrossProfileCalendarPackages_reopenDpms()7084     public void testCrossProfileCalendarPackages_reopenDpms() {
7085         setAsProfileOwner(admin1);
7086         dpm.setCrossProfileCalendarPackages(admin1, null);
7087         Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
7088         assertThat(packages == null).isTrue();
7089         initializeDpms();
7090         packages = dpm.getCrossProfileCalendarPackages(admin1);
7091         assertThat(packages == null).isTrue();
7092 
7093         dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
7094         packages = dpm.getCrossProfileCalendarPackages(admin1);
7095         assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
7096         initializeDpms();
7097         packages = dpm.getCrossProfileCalendarPackages(admin1);
7098         assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
7099 
7100         final String dummyPackageName = "test";
7101         final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
7102         dpm.setCrossProfileCalendarPackages(admin1, testPackages);
7103         packages = dpm.getCrossProfileCalendarPackages(admin1);
7104         assertCrossProfileCalendarPackagesEqual(packages, testPackages);
7105         initializeDpms();
7106         packages = dpm.getCrossProfileCalendarPackages(admin1);
7107         assertCrossProfileCalendarPackagesEqual(packages, testPackages);
7108     }
7109 
assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual)7110     private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
7111         assertThat(expected).isNotNull();
7112         assertThat(actual).isNotNull();
7113         assertThat(actual).containsExactlyElementsIn(expected);
7114     }
7115 
7116     @Test
testIsPackageAllowedToAccessCalendar_adminNotAllowed()7117     public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
7118         final String testPackage = "TEST_PACKAGE";
7119         setAsProfileOwner(admin1);
7120         dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
7121         when(getServices().settings.settingsSecureGetIntForUser(
7122                 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
7123                 0, CALLER_USER_HANDLE)).thenReturn(1);
7124         mContext.permissions.add(permission.INTERACT_ACROSS_USERS);
7125 
7126         assertThat(dpm.isPackageAllowedToAccessCalendar(testPackage)).isFalse();
7127     }
7128 
7129     @Test
testIsPackageAllowedToAccessCalendar_settingOff()7130     public void testIsPackageAllowedToAccessCalendar_settingOff() {
7131         final String testPackage = "TEST_PACKAGE";
7132         setAsProfileOwner(admin1);
7133         dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
7134         when(getServices().settings.settingsSecureGetIntForUser(
7135                 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
7136                 0, CALLER_USER_HANDLE)).thenReturn(0);
7137         mContext.permissions.add(permission.INTERACT_ACROSS_USERS);
7138 
7139         assertThat(dpm.isPackageAllowedToAccessCalendar(testPackage)).isFalse();
7140     }
7141 
7142     @Test
testIsPackageAllowedToAccessCalendar_bothAllowed()7143     public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
7144         final String testPackage = "TEST_PACKAGE";
7145         getServices().addTestPackageUid(testPackage, DpmMockContext.ANOTHER_UID);
7146         setAsProfileOwner(admin1);
7147         dpm.setCrossProfileCalendarPackages(admin1, null);
7148         when(getServices().settings.settingsSecureGetIntForUser(
7149                 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
7150                 0, CALLER_USER_HANDLE)).thenReturn(1);
7151         mContext.permissions.add(permission.INTERACT_ACROSS_USERS);
7152 
7153         assertThat(dpm.isPackageAllowedToAccessCalendar(testPackage)).isTrue();
7154     }
7155 
7156     @Test
testIsPackageAllowedToAccessCalendar_requiresPermission()7157     public void testIsPackageAllowedToAccessCalendar_requiresPermission() {
7158         final String testPackage = "TEST_PACKAGE";
7159         getServices().addTestPackageUid(testPackage, DpmMockContext.ANOTHER_UID);
7160 
7161         assertExpectException(SecurityException.class, /* messageRegex= */ null,
7162                 () -> dpm.isPackageAllowedToAccessCalendar(testPackage));
7163     }
7164 
7165     @Test
testIsPackageAllowedToAccessCalendar_samePackageAndSameUser_noPermissionRequired()7166     public void testIsPackageAllowedToAccessCalendar_samePackageAndSameUser_noPermissionRequired() {
7167         final String testPackage = "TEST_PACKAGE";
7168         setAsProfileOwner(admin1);
7169         dpm.setCrossProfileCalendarPackages(admin1, null);
7170         when(getServices().settings.settingsSecureGetIntForUser(
7171                 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
7172                 0, CALLER_USER_HANDLE)).thenReturn(1);
7173 
7174         getServices().addTestPackageUid(testPackage, mContext.binder.callingUid);
7175 
7176         assertThat(dpm.isPackageAllowedToAccessCalendar(testPackage)).isTrue();
7177     }
7178 
7179     @Test
7180     @Ignore("b/277916462")
testSetUserControlDisabledPackages_asDO()7181     public void testSetUserControlDisabledPackages_asDO() throws Exception {
7182         final List<String> testPackages = new ArrayList<>();
7183         testPackages.add("package_1");
7184         testPackages.add("package_2");
7185         mServiceContext.permissions.add(permission.MANAGE_DEVICE_ADMINS);
7186         setDeviceOwner();
7187 
7188         dpm.setUserControlDisabledPackages(admin1, testPackages);
7189 
7190         verify(getServices().packageManagerInternal)
7191                 .setOwnerProtectedPackages(UserHandle.USER_ALL, testPackages);
7192         assertThat(dpm.getUserControlDisabledPackages(admin1)).isEqualTo(testPackages);
7193     }
7194 
7195     @Test
7196     @Ignore("b/277916462")
testSetUserControlDisabledPackages_asPO()7197     public void testSetUserControlDisabledPackages_asPO() {
7198         final List<String> testPackages = new ArrayList<>();
7199         testPackages.add("package_1");
7200         testPackages.add("package_2");
7201         mServiceContext.permissions.add(permission.MANAGE_DEVICE_ADMINS);
7202         setAsProfileOwner(admin1);
7203 
7204         dpm.setUserControlDisabledPackages(admin1, testPackages);
7205 
7206         verify(getServices().packageManagerInternal)
7207                 .setOwnerProtectedPackages(CALLER_USER_HANDLE, testPackages);
7208         assertThat(dpm.getUserControlDisabledPackages(admin1)).isEqualTo(testPackages);
7209     }
7210 
configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId)7211     private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
7212         final long ident = mServiceContext.binder.clearCallingIdentity();
7213         mServiceContext.binder.callingUid = UserHandle.getUid(userId, DpmMockContext.SYSTEM_UID);
7214 
7215         configureContextForAccess(mServiceContext, true);
7216         runAsCaller(mServiceContext, dpms, dpm -> {
7217             dpm.setProfileOwnerOnOrganizationOwnedDevice(who, true);
7218         });
7219         mServiceContext.binder.restoreCallingIdentity(ident);
7220     }
7221 
7222     @Test
testGetCrossProfilePackages_notSet_returnsEmpty()7223     public void testGetCrossProfilePackages_notSet_returnsEmpty() {
7224         setAsProfileOwner(admin1);
7225         assertThat(dpm.getCrossProfilePackages(admin1).isEmpty()).isTrue();
7226     }
7227 
7228     @Test
testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty()7229     public void testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() {
7230         setAsProfileOwner(admin1);
7231 
7232         initializeDpms();
7233 
7234         assertThat(dpm.getCrossProfilePackages(admin1).isEmpty()).isTrue();
7235     }
7236 
7237     @Test
testGetCrossProfilePackages_whenSet_returnsEqual()7238     public void testGetCrossProfilePackages_whenSet_returnsEqual() {
7239         setAsProfileOwner(admin1);
7240         Set<String> packages = Collections.singleton("TEST_PACKAGE");
7241 
7242         dpm.setCrossProfilePackages(admin1, packages);
7243 
7244         assertThat(dpm.getCrossProfilePackages(admin1)).isEqualTo(packages);
7245     }
7246 
7247     @Test
testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual()7248     public void testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual() {
7249         setAsProfileOwner(admin1);
7250         Set<String> packages = Collections.singleton("TEST_PACKAGE");
7251 
7252         dpm.setCrossProfilePackages(admin1, packages);
7253         initializeDpms();
7254 
7255         assertThat(dpm.getCrossProfilePackages(admin1)).isEqualTo(packages);
7256     }
7257 
7258     @Test
testGetAllCrossProfilePackages_notSet_returnsEmpty()7259     public void testGetAllCrossProfilePackages_notSet_returnsEmpty() throws Exception {
7260         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
7261         addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
7262         mContext.packageName = admin1.getPackageName();
7263 
7264         setCrossProfileAppsList();
7265         setVendorCrossProfileAppsList();
7266 
7267         assertThat(dpm.getAllCrossProfilePackages().isEmpty()).isTrue();
7268     }
7269 
7270     @Test
testGetAllCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty()7271     public void testGetAllCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty()
7272             throws Exception {
7273         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
7274         addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
7275         mContext.packageName = admin1.getPackageName();
7276 
7277         setCrossProfileAppsList();
7278         setVendorCrossProfileAppsList();
7279         initializeDpms();
7280 
7281         assertThat(dpm.getAllCrossProfilePackages().isEmpty()).isTrue();
7282     }
7283 
7284     @Test
testGetAllCrossProfilePackages_whenSet_returnsCombinedSet()7285     public void testGetAllCrossProfilePackages_whenSet_returnsCombinedSet() throws Exception {
7286         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
7287         addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
7288         final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
7289         mContext.packageName = admin1.getPackageName();
7290 
7291         dpm.setCrossProfilePackages(admin1, packages);
7292         setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
7293         setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE");
7294 
7295         assertThat(dpm.getAllCrossProfilePackages()).containsExactly(
7296                 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE",
7297                 "TEST_VENDOR_DEFAULT_PACKAGE");
7298     }
7299 
7300     @Test
testGetAllCrossProfilePackages_whenSet_dpmsReinitialized_returnsCombinedSet()7301     public void testGetAllCrossProfilePackages_whenSet_dpmsReinitialized_returnsCombinedSet()
7302             throws Exception {
7303         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
7304         addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
7305         final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
7306         mContext.packageName = admin1.getPackageName();
7307 
7308         dpm.setCrossProfilePackages(admin1, packages);
7309         setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
7310         setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE");
7311         initializeDpms();
7312 
7313         assertThat(dpm.getAllCrossProfilePackages()).containsExactly(
7314                 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE",
7315                 "TEST_VENDOR_DEFAULT_PACKAGE");
7316     }
7317 
7318     @Test
testGetDefaultCrossProfilePackages_noPackagesSet_returnsEmpty()7319     public void testGetDefaultCrossProfilePackages_noPackagesSet_returnsEmpty() {
7320         setCrossProfileAppsList();
7321         setVendorCrossProfileAppsList();
7322 
7323         assertThat(dpm.getDefaultCrossProfilePackages()).isEmpty();
7324     }
7325 
7326     @Test
testGetDefaultCrossProfilePackages_packagesSet_returnsCombinedSet()7327     public void testGetDefaultCrossProfilePackages_packagesSet_returnsCombinedSet() {
7328         setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
7329         setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE");
7330 
7331         assertThat(dpm.getDefaultCrossProfilePackages()).containsExactly(
7332                 "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", "TEST_VENDOR_DEFAULT_PACKAGE");
7333     }
7334 
7335     @Test
testSetCommonCriteriaMode_asDeviceOwner()7336     public void testSetCommonCriteriaMode_asDeviceOwner() throws Exception {
7337         setDeviceOwner();
7338 
7339         assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isFalse();
7340         assertThat(dpm.isCommonCriteriaModeEnabled(null)).isFalse();
7341 
7342         dpm.setCommonCriteriaModeEnabled(admin1, true);
7343 
7344         assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isTrue();
7345         assertThat(dpm.isCommonCriteriaModeEnabled(null)).isTrue();
7346     }
7347 
7348     @Test
testSetCommonCriteriaMode_asPoOfOrgOwnedDevice()7349     public void testSetCommonCriteriaMode_asPoOfOrgOwnedDevice() throws Exception {
7350         final int managedProfileUserId = 15;
7351         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
7352         addManagedProfile(admin1, managedProfileAdminUid, admin1);
7353         configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
7354         mContext.binder.callingUid = managedProfileAdminUid;
7355 
7356         assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isFalse();
7357         assertThat(dpm.isCommonCriteriaModeEnabled(null)).isFalse();
7358 
7359         dpm.setCommonCriteriaModeEnabled(admin1, true);
7360 
7361         assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isTrue();
7362         assertThat(dpm.isCommonCriteriaModeEnabled(null)).isTrue();
7363     }
7364 
7365     @Test
testCanProfileOwnerResetPasswordWhenLocked_nonDirectBootAwarePo()7366     public void testCanProfileOwnerResetPasswordWhenLocked_nonDirectBootAwarePo()
7367             throws Exception {
7368         setDeviceEncryptionPerUser();
7369         setupProfileOwner();
7370         setupPasswordResetToken();
7371 
7372         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7373         assertWithMessage("po is not direct boot aware")
7374                 .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isFalse();
7375     }
7376 
7377     @Test
testCanProfileOwnerResetPasswordWhenLocked_noActiveToken()7378     public void testCanProfileOwnerResetPasswordWhenLocked_noActiveToken() throws Exception {
7379         setDeviceEncryptionPerUser();
7380         setupProfileOwner();
7381         makeAdmin1DirectBootAware();
7382 
7383         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7384         assertWithMessage("po doesn't have an active password reset token")
7385                 .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isFalse();
7386     }
7387 
7388     @Test
testCanProfileOwnerResetPasswordWhenLocked_nonFbeDevice()7389     public void testCanProfileOwnerResetPasswordWhenLocked_nonFbeDevice() throws Exception {
7390         setupProfileOwner();
7391         makeAdmin1DirectBootAware();
7392         setupPasswordResetToken();
7393 
7394         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7395         assertWithMessage("device is not FBE")
7396                 .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isFalse();
7397     }
7398 
7399     @Test
7400     @Ignore("b/277916462")
testCanProfileOwnerResetPasswordWhenLocked()7401     public void testCanProfileOwnerResetPasswordWhenLocked() throws Exception {
7402         setDeviceEncryptionPerUser();
7403         setupProfileOwner();
7404         makeAdmin1DirectBootAware();
7405         setupPasswordResetToken();
7406 
7407         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7408         assertWithMessage("direct boot aware po with active password reset token")
7409                 .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isTrue();
7410     }
7411 
setupPasswordResetToken()7412     private void setupPasswordResetToken() {
7413         final byte[] token = new byte[32];
7414         final long handle = 123456;
7415 
7416         when(getServices().lockPatternUtils
7417                 .addEscrowToken(eq(token), eq(CALLER_USER_HANDLE),
7418                         nullable(EscrowTokenStateChangeCallback.class)))
7419                 .thenReturn(handle);
7420 
7421         dpm.setResetPasswordToken(admin1, token);
7422 
7423         when(getServices().lockPatternUtils
7424                 .isEscrowTokenActive(eq(handle), eq(CALLER_USER_HANDLE)))
7425                 .thenReturn(true);
7426 
7427         assertWithMessage("failed to activate token").that(dpm.isResetPasswordTokenActive(admin1))
7428                 .isTrue();
7429     }
7430 
makeAdmin1DirectBootAware()7431     private void makeAdmin1DirectBootAware()
7432             throws PackageManager.NameNotFoundException, android.os.RemoteException {
7433         Mockito.reset(getServices().ipackageManager);
7434 
7435         final ApplicationInfo ai = DpmTestUtils.cloneParcelable(
7436                 mRealTestContext.getPackageManager().getApplicationInfo(
7437                         admin1.getPackageName(),
7438                         PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS));
7439         ai.privateFlags = PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7440 
7441         doReturn(ai).when(getServices().ipackageManager).getApplicationInfo(
7442                 eq(admin1.getPackageName()),
7443                 anyLong(),
7444                 eq(CALLER_USER_HANDLE));
7445     }
7446 
setDeviceEncryptionPerUser()7447     private void setDeviceEncryptionPerUser() {
7448         when(getServices().storageManager.isFileBasedEncryptionEnabled()).thenReturn(true);
7449     }
7450 
setCrossProfileAppsList(String... packages)7451     private void setCrossProfileAppsList(String... packages) {
7452         when(mContext.getResources()
7453                 .getStringArray(eq(R.array.cross_profile_apps)))
7454                 .thenReturn(packages);
7455     }
7456 
setVendorCrossProfileAppsList(String... packages)7457     private void setVendorCrossProfileAppsList(String... packages) {
7458         when(mContext.getResources()
7459                 .getStringArray(eq(R.array.vendor_cross_profile_apps)))
7460                 .thenReturn(packages);
7461     }
7462 
7463     @Test
7464     @Ignore("b/277916462")
testSetAccountTypesWithManagementDisabledOnManagedProfile()7465     public void testSetAccountTypesWithManagementDisabledOnManagedProfile() throws Exception {
7466         setupProfileOwner();
7467 
7468         final String accountType = "com.example.account.type";
7469         int originalUid = mContext.binder.callingUid;
7470         dpm.setAccountManagementDisabled(admin1, accountType, true);
7471         assertThat(dpm.getAccountTypesWithManagementDisabled()).asList().containsExactly(
7472                 accountType);
7473         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
7474         assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
7475         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7476         assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
7477 
7478         mContext.binder.callingUid = originalUid;
7479         dpm.setAccountManagementDisabled(admin1, accountType, false);
7480         assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
7481     }
7482 
7483     @Test
7484     @Ignore("b/277916462")
testSetAccountTypesWithManagementDisabledOnOrgOwnedManagedProfile()7485     public void testSetAccountTypesWithManagementDisabledOnOrgOwnedManagedProfile()
7486             throws Exception {
7487         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
7488 
7489         final int managedProfileUserId = 15;
7490         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
7491 
7492         addManagedProfile(admin1, managedProfileAdminUid, admin1);
7493         mContext.binder.callingUid = managedProfileAdminUid;
7494 
7495         configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
7496 
7497         int originalUid = mContext.binder.callingUid;
7498         final String accountType = "com.example.account.type";
7499         dpm.getParentProfileInstance(admin1).setAccountManagementDisabled(admin1, accountType,
7500                 true);
7501         assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
7502         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
7503         assertThat(dpm.getAccountTypesWithManagementDisabled()).asList().containsExactly(
7504                 accountType);
7505         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7506         assertThat(dpm.getAccountTypesWithManagementDisabled()).asList().containsExactly(
7507                 accountType);
7508 
7509         mContext.binder.callingUid = originalUid;
7510         dpm.getParentProfileInstance(admin1).setAccountManagementDisabled(admin1, accountType,
7511                 false);
7512         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
7513         assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
7514         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7515         assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
7516     }
7517 
7518     /**
7519      * Tests the case when the user doesn't turn the profile on in time, verifies that the user is
7520      * warned with a notification and then the apps get suspended.
7521      */
7522     @Test
7523     @Ignore // Temp disabled - broken with flags
testMaximumProfileTimeOff_profileOffTimeExceeded()7524     public void testMaximumProfileTimeOff_profileOffTimeExceeded() throws Exception {
7525         prepareMocksForSetMaximumProfileTimeOff();
7526 
7527         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7528         dpm.setManagedProfileMaximumTimeOff(admin1, PROFILE_OFF_TIMEOUT);
7529 
7530         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7531         // The profile is running, neither alarm nor notification should be posted.
7532         verify(getServices().alarmManager, never())
7533                 .set(anyInt(), anyLong(), any(PendingIntent.class));
7534         verify(getServices().notificationManager, never())
7535                 .notify(anyInt(), any(Notification.class));
7536         // Apps shouldn't be suspended.
7537         verifyNoMoreInteractions(getServices().ipackageManager);
7538         clearInvocations(getServices().alarmManager);
7539 
7540         setUserUnlocked(CALLER_USER_HANDLE, false);
7541         sendBroadcastWithUser(dpms, Intent.ACTION_USER_STOPPED, CALLER_USER_HANDLE);
7542 
7543         // Verify the alarm was scheduled for time when the warning should be shown.
7544         verify(getServices().alarmManager, times(1))
7545                 .set(anyInt(), eq(PROFILE_OFF_WARNING_TIME), any());
7546         // But still no notification should be posted at this point.
7547         verify(getServices().notificationManager, never())
7548                 .notify(anyInt(), any(Notification.class));
7549         // Apps shouldn't be suspended.
7550         verifyNoMoreInteractions(getServices().ipackageManager);
7551         clearInvocations(getServices().alarmManager);
7552 
7553         // Pretend the alarm went off.
7554         dpms.mMockInjector.setSystemCurrentTimeMillis(PROFILE_OFF_WARNING_TIME + 10);
7555         sendBroadcastWithUser(dpms, ACTION_PROFILE_OFF_DEADLINE, CALLER_USER_HANDLE);
7556 
7557         // Verify the alarm was scheduled for the actual deadline this time.
7558         verify(getServices().alarmManager, times(1)).set(anyInt(), eq(PROFILE_OFF_DEADLINE), any());
7559         // Now the user should see a warning notification.
7560         verify(getServices().notificationManager, times(1))
7561                 .notifyAsUser(any(), anyInt(), any(), any());
7562         // Apps shouldn't be suspended yet.
7563         verifyNoMoreInteractions(getServices().ipackageManager);
7564         clearInvocations(getServices().alarmManager);
7565         clearInvocations(getServices().notificationManager);
7566 
7567         // Pretend the alarm went off.
7568         dpms.mMockInjector.setSystemCurrentTimeMillis(PROFILE_OFF_DEADLINE + 10);
7569         sendBroadcastWithUser(dpms, ACTION_PROFILE_OFF_DEADLINE, CALLER_USER_HANDLE);
7570 
7571         // Verify the alarm was not set.
7572         verifyNoMoreInteractions(getServices().alarmManager);
7573         // Now the user should see a notification about suspended apps.
7574         verify(getServices().notificationManager, times(1))
7575                 .notifyAsUser(any(), anyInt(), any(), any());
7576         // Verify that the apps are suspended.
7577         verify(getServices().packageManagerInternal, times(1))
7578                 .setPackagesSuspendedByAdmin(anyInt(), any(), eq(true));
7579     }
7580 
7581     /**
7582      * Tests the case when the user turns the profile back on long before the deadline (> 1 day).
7583      */
7584     @Test
testMaximumProfileTimeOff_turnOnBeforeWarning()7585     public void testMaximumProfileTimeOff_turnOnBeforeWarning() throws Exception {
7586         prepareMocksForSetMaximumProfileTimeOff();
7587 
7588         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7589         dpm.setManagedProfileMaximumTimeOff(admin1, PROFILE_OFF_TIMEOUT);
7590 
7591         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7592         setUserUnlocked(CALLER_USER_HANDLE, false);
7593         sendBroadcastWithUser(dpms, Intent.ACTION_USER_STOPPED, CALLER_USER_HANDLE);
7594         clearInvocations(getServices().alarmManager);
7595         setUserUnlocked(CALLER_USER_HANDLE, true);
7596         sendBroadcastWithUser(dpms, Intent.ACTION_USER_UNLOCKED, CALLER_USER_HANDLE);
7597 
7598         // Verify that the alarm got discharged.
7599         verify(getServices().alarmManager, times(1)).cancel((PendingIntent) null);
7600     }
7601 
7602     /**
7603      * Tests the case when the user turns the profile back on after the warning notification.
7604      */
7605     @Test
testMaximumProfileTimeOff_turnOnAfterWarning()7606     public void testMaximumProfileTimeOff_turnOnAfterWarning() throws Exception {
7607         prepareMocksForSetMaximumProfileTimeOff();
7608 
7609         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7610         dpm.setManagedProfileMaximumTimeOff(admin1, PROFILE_OFF_TIMEOUT);
7611 
7612         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7613         setUserUnlocked(CALLER_USER_HANDLE, false);
7614         sendBroadcastWithUser(dpms, Intent.ACTION_USER_STOPPED, CALLER_USER_HANDLE);
7615 
7616         // Pretend the alarm went off.
7617         dpms.mMockInjector.setSystemCurrentTimeMillis(PROFILE_OFF_WARNING_TIME + 10);
7618         sendBroadcastWithUser(dpms, ACTION_PROFILE_OFF_DEADLINE, CALLER_USER_HANDLE);
7619 
7620         clearInvocations(getServices().alarmManager);
7621         clearInvocations(getServices().notificationManager);
7622         setUserUnlocked(CALLER_USER_HANDLE, true);
7623         sendBroadcastWithUser(dpms, Intent.ACTION_USER_UNLOCKED, CALLER_USER_HANDLE);
7624 
7625         // Verify that the alarm got discharged.
7626         verify(getServices().alarmManager, times(1)).cancel((PendingIntent) null);
7627         // Verify that the notification is removed.
7628         verify(getServices().notificationManager, times(1))
7629                 .cancel(eq(SystemMessageProto.SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED));
7630     }
7631 
7632     /**
7633      * Tests the case when the user turns the profile back on when the apps are already suspended.
7634      */
7635     @Test
7636     @Ignore("b/277916462")
testMaximumProfileTimeOff_turnOnAfterDeadline()7637     public void testMaximumProfileTimeOff_turnOnAfterDeadline() throws Exception {
7638         prepareMocksForSetMaximumProfileTimeOff();
7639 
7640         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7641         dpm.setManagedProfileMaximumTimeOff(admin1, PROFILE_OFF_TIMEOUT);
7642 
7643         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
7644         setUserUnlocked(CALLER_USER_HANDLE, false);
7645         sendBroadcastWithUser(dpms, Intent.ACTION_USER_STOPPED, CALLER_USER_HANDLE);
7646 
7647         // Pretend the alarm went off after the deadline.
7648         dpms.mMockInjector.setSystemCurrentTimeMillis(PROFILE_OFF_DEADLINE + 10);
7649         sendBroadcastWithUser(dpms, ACTION_PROFILE_OFF_DEADLINE, CALLER_USER_HANDLE);
7650 
7651         clearInvocations(getServices().alarmManager);
7652         clearInvocations(getServices().notificationManager);
7653         clearInvocations(getServices().ipackageManager);
7654 
7655         // Pretend the user clicked on the "apps suspended" notification to turn the profile on.
7656         sendBroadcastWithUser(dpms, ACTION_TURN_PROFILE_ON_NOTIFICATION, CALLER_USER_HANDLE);
7657         // Verify that the profile is turned on.
7658         verify(getServices().userManager, times(1))
7659                 .requestQuietModeEnabled(eq(false), eq(UserHandle.of(CALLER_USER_HANDLE)));
7660 
7661         setUserUnlocked(CALLER_USER_HANDLE, true);
7662         sendBroadcastWithUser(dpms, Intent.ACTION_USER_UNLOCKED, CALLER_USER_HANDLE);
7663 
7664         // Verify that the notification is removed (at this point DPC should show it).
7665         verify(getServices().notificationManager, times(1))
7666                 .cancel(eq(SystemMessageProto.SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED));
7667         // Verify that the apps are NOT unsuspeded.
7668         verify(getServices().ipackageManager, never()).setPackagesSuspendedAsUser(
7669                 any(), eq(false), any(), any(), any(), anyInt(), any(), anyInt(), anyInt());
7670         // Verify that DPC is invoked to check policy compliance.
7671         verify(mContext.spiedContext).startActivityAsUser(
7672                 MockUtils.checkIntentAction(ACTION_CHECK_POLICY_COMPLIANCE),
7673                 MockUtils.checkUserHandle(CALLER_USER_HANDLE));
7674 
7675         // Verify that correct suspension reason is reported to the DPC.
7676         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7677         assertThat(dpm.getPersonalAppsSuspendedReasons(admin1))
7678                 .isEqualTo(DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT);
7679 
7680         // Verify that rolling time back doesn't change the status.
7681         dpms.mMockInjector.setSystemCurrentTimeMillis(PROFILE_OFF_START);
7682         assertThat(dpm.getPersonalAppsSuspendedReasons(admin1))
7683                 .isEqualTo(DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT);
7684     }
7685 
7686     @Test
testSetRequiredPasswordComplexity_UnauthorizedCallersOnDO()7687     public void testSetRequiredPasswordComplexity_UnauthorizedCallersOnDO() throws Exception {
7688         assumeDeprecatedPasswordApisSupported();
7689 
7690         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
7691         setupDeviceOwner();
7692         // DO must be able to set it.
7693         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW);
7694         // But not on the parent DPM.
7695         assertExpectException(IllegalArgumentException.class, null,
7696                 () -> parentDpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW));
7697         // Another package must not be allowed to set password complexity.
7698         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
7699         assertExpectException(SecurityException.class, null,
7700                 () -> dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW));
7701     }
7702 
7703     @Test
testSetRequiredPasswordComplexity_UnauthorizedCallersOnPO()7704     public void testSetRequiredPasswordComplexity_UnauthorizedCallersOnPO() throws Exception {
7705         assumeDeprecatedPasswordApisSupported();
7706 
7707         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7708         setupProfileOwner();
7709         // PO must be able to set it.
7710         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW);
7711         // And on the parent profile DPM instance.
7712         parentDpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW);
7713         // Another package must not be allowed to set password complexity.
7714         mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
7715         assertExpectException(SecurityException.class, null,
7716                 () -> dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_LOW));
7717     }
7718 
7719     @Test
testSetRequiredPasswordComplexity_validValuesOnly()7720     public void testSetRequiredPasswordComplexity_validValuesOnly() throws Exception {
7721         assumeDeprecatedPasswordApisSupported();
7722 
7723         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7724         setupProfileOwner();
7725 
7726         // Cannot set value other than password_complexity none/low/medium/high
7727         assertExpectException(IllegalArgumentException.class, null, () ->
7728                 dpm.setRequiredPasswordComplexity(-1));
7729         assertExpectException(IllegalArgumentException.class, null, () ->
7730                 dpm.setRequiredPasswordComplexity(7));
7731         assertExpectException(IllegalArgumentException.class, null, () ->
7732                 dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH + 1));
7733 
7734         final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
7735                 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
7736         for (int complexity : allowedModes) {
7737             // Ensure exception is not thrown.
7738             dpm.setRequiredPasswordComplexity(complexity);
7739         }
7740     }
7741 
7742     @Test
testSetRequiredPasswordComplexity_setAndGet()7743     public void testSetRequiredPasswordComplexity_setAndGet() throws Exception {
7744         assumeDeprecatedPasswordApisSupported();
7745 
7746         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7747         setupProfileOwner();
7748 
7749         final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
7750                 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
7751         for (int complexity : allowedModes) {
7752             dpm.setRequiredPasswordComplexity(complexity);
7753             assertThat(dpm.getRequiredPasswordComplexity()).isEqualTo(complexity);
7754         }
7755     }
7756 
7757     @Test
testSetRequiredPasswordComplexityOnParent_setAndGet()7758     public void testSetRequiredPasswordComplexityOnParent_setAndGet() throws Exception {
7759         assumeDeprecatedPasswordApisSupported();
7760 
7761         final int managedProfileUserId = 15;
7762         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
7763 
7764         addManagedProfile(admin1, managedProfileAdminUid, admin1);
7765         mContext.binder.callingUid = managedProfileAdminUid;
7766         when(getServices().userManager.isManagedProfile()).thenReturn(true);
7767 
7768         final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
7769                 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
7770         for (int complexity : allowedModes) {
7771             dpm.getParentProfileInstance(admin1).setRequiredPasswordComplexity(complexity);
7772             assertThat(dpm.getParentProfileInstance(admin1).getRequiredPasswordComplexity())
7773                     .isEqualTo(complexity);
7774             assertThat(dpm.getRequiredPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE);
7775         }
7776     }
7777 
7778     @Test
testSetRequiredPasswordComplexity_isSufficient()7779     public void testSetRequiredPasswordComplexity_isSufficient() throws Exception {
7780         assumeDeprecatedPasswordApisSupported();
7781 
7782         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
7783         mContext.packageName = admin1.getPackageName();
7784         setupDeviceOwner();
7785 
7786         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
7787         assertThat(dpm.getRequiredPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_HIGH);
7788         when(getServices().packageManager.getPackagesForUid(
7789                 DpmMockContext.CALLER_SYSTEM_USER_UID)).thenReturn(new String[0]);
7790         mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
7791         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE);
7792 
7793         reset(mContext.spiedContext);
7794         PasswordMetrics passwordMetricsNoSymbols = metricsForPin("1234");
7795         setActivePasswordState(passwordMetricsNoSymbols);
7796         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_LOW);
7797         assertThat(dpm.isActivePasswordSufficient()).isFalse();
7798 
7799         reset(mContext.spiedContext);
7800         passwordMetricsNoSymbols = metricsForPassword("84125312943a");
7801         setActivePasswordState(passwordMetricsNoSymbols);
7802         assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_HIGH);
7803         // using isActivePasswordSufficient
7804         assertThat(dpm.isActivePasswordSufficient()).isTrue();
7805     }
7806 
7807     @Test
testSetRequiredPasswordComplexity_resetBySettingQuality()7808     public void testSetRequiredPasswordComplexity_resetBySettingQuality() throws Exception {
7809         assumeDeprecatedPasswordApisSupported();
7810 
7811         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7812         setupProfileOwner();
7813 
7814         // Test that calling setPasswordQuality resets complexity to none.
7815         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
7816         assertThat(dpm.getRequiredPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_HIGH);
7817         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX);
7818         assertThat(dpm.getRequiredPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE);
7819     }
7820 
7821     @Test
testSetRequiredPasswordComplexity_overridesQuality()7822     public void testSetRequiredPasswordComplexity_overridesQuality() throws Exception {
7823         assumeDeprecatedPasswordApisSupported();
7824 
7825         mContext.binder.callingUid = DpmMockContext.CALLER_UID;
7826         setupProfileOwner();
7827 
7828         // Test that calling setRequiredPasswordComplexity resets password quality.
7829         dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX);
7830         assertThat(dpm.getPasswordQuality(admin1)).isEqualTo(
7831                 DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX);
7832         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
7833         assertThat(dpm.getPasswordQuality(admin1)).isEqualTo(
7834                 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
7835     }
7836 
7837     @Test
testSetRequiredPasswordComplexityFailsWithQualityOnParent()7838     public void testSetRequiredPasswordComplexityFailsWithQualityOnParent() throws Exception {
7839         assumeDeprecatedPasswordApisSupported();
7840 
7841         final int managedProfileUserId = CALLER_USER_HANDLE;
7842         final int managedProfileAdminUid =
7843                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
7844         mContext.binder.callingUid = managedProfileAdminUid;
7845         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
7846 
7847         parentDpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
7848 
7849         assertThrows(IllegalStateException.class,
7850                 () -> dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH));
7851     }
7852 
7853     @Test
testSetQualityOnParentFailsWithComplexityOnProfile()7854     public void testSetQualityOnParentFailsWithComplexityOnProfile() throws Exception {
7855         assumeDeprecatedPasswordApisSupported();
7856 
7857         final int managedProfileUserId = CALLER_USER_HANDLE;
7858         final int managedProfileAdminUid =
7859                 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
7860         mContext.binder.callingUid = managedProfileAdminUid;
7861         addManagedProfile(admin1, managedProfileAdminUid, admin1, VERSION_CODES.R);
7862 
7863         dpm.setRequiredPasswordComplexity(PASSWORD_COMPLEXITY_HIGH);
7864 
7865         assertThrows(IllegalStateException.class,
7866                 () -> parentDpm.setPasswordQuality(admin1,
7867                         DevicePolicyManager.PASSWORD_QUALITY_COMPLEX));
7868     }
7869 
7870     @Test
testSetDeviceOwnerType_throwsExceptionWhenCallerNotAuthorized()7871     public void testSetDeviceOwnerType_throwsExceptionWhenCallerNotAuthorized() {
7872         assertThrows(SecurityException.class,
7873                 () -> dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_DEFAULT));
7874     }
7875 
7876     @Test
testSetDeviceOwnerType_throwsExceptionWhenThereIsNoDeviceOwner()7877     public void testSetDeviceOwnerType_throwsExceptionWhenThereIsNoDeviceOwner() {
7878         mContext.binder.clearCallingIdentity();
7879         assertThrows(IllegalStateException.class,
7880                 () -> dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_DEFAULT));
7881     }
7882 
7883     @Test
testSetDeviceOwnerType_throwsExceptionWhenNotAsDeviceOwnerAdmin()7884     public void testSetDeviceOwnerType_throwsExceptionWhenNotAsDeviceOwnerAdmin() throws Exception {
7885         setDeviceOwner();
7886 
7887         assertThrows(IllegalStateException.class,
7888                 () -> dpm.setDeviceOwnerType(admin2, DEVICE_OWNER_TYPE_FINANCED));
7889     }
7890 
7891     @Test
testSetDeviceOwnerType_asDeviceOwner_toFinancedDevice()7892     public void testSetDeviceOwnerType_asDeviceOwner_toFinancedDevice() throws Exception {
7893         setDeviceOwner();
7894 
7895         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
7896 
7897         assertThat(dpm.isFinancedDevice()).isTrue();
7898         initializeDpms();
7899         assertThat(dpm.isFinancedDevice()).isTrue();
7900     }
7901 
7902     @Test
testSetDeviceOwnerType_asDeviceOwner_setDeviceOwnerTypeTwice_success()7903     public void testSetDeviceOwnerType_asDeviceOwner_setDeviceOwnerTypeTwice_success()
7904             throws Exception {
7905         setDeviceOwner();
7906         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_DEFAULT);
7907 
7908         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
7909 
7910         assertThat(dpm.isFinancedDevice()).isTrue();
7911     }
7912 
7913     @Test
testIsFinancedDevice_throwsExceptionWhenThereIsNoDeviceOwner()7914     public void testIsFinancedDevice_throwsExceptionWhenThereIsNoDeviceOwner() {
7915         assertThrows(SecurityException.class, () -> dpm.isFinancedDevice());
7916     }
7917 
7918     @Test
testSetUserRestriction_financeDo_invalidRestrictions_restrictionNotSet()7919     public void testSetUserRestriction_financeDo_invalidRestrictions_restrictionNotSet()
7920             throws Exception {
7921         setDeviceOwner();
7922         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
7923 
7924         for (String restriction : UserRestrictionsUtils.USER_RESTRICTIONS) {
7925             if (!UserRestrictionsUtils.canFinancedDeviceOwnerChange(restriction)) {
7926                 assertNoDeviceOwnerRestrictions();
7927                 assertExpectException(SecurityException.class, /* messageRegex= */ null,
7928                         () -> dpm.addUserRestriction(admin1, restriction));
7929 
7930                 verify(getServices().userManagerInternal, never())
7931                         .setDevicePolicyUserRestrictions(anyInt(), any(), any(), anyBoolean());
7932                 DpmTestUtils.assertRestrictions(new Bundle(), dpm.getUserRestrictions(admin1));
7933             }
7934         }
7935     }
7936 
7937     @Test
7938     @Ignore("b/277916462")
testSetUserRestriction_financeDo_validRestrictions_setsRestriction()7939     public void testSetUserRestriction_financeDo_validRestrictions_setsRestriction()
7940             throws Exception {
7941         setDeviceOwner();
7942         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
7943 
7944         for (String restriction : UserRestrictionsUtils.USER_RESTRICTIONS) {
7945             if (UserRestrictionsUtils.canFinancedDeviceOwnerChange(restriction)) {
7946                 assertNoDeviceOwnerRestrictions();
7947                 dpm.addUserRestriction(admin1, restriction);
7948 
7949                 Bundle globalRestrictions =
7950                         dpms.getDeviceOwnerAdminLocked().getGlobalUserRestrictions(
7951                                 UserManagerInternal.OWNER_TYPE_DEVICE_OWNER);
7952                 RestrictionsSet localRestrictions = new RestrictionsSet();
7953                 localRestrictions.updateRestrictions(
7954                         UserHandle.USER_SYSTEM,
7955                         dpms.getDeviceOwnerAdminLocked().getLocalUserRestrictions(
7956                                 UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
7957                 verify(getServices().userManagerInternal)
7958                         .setDevicePolicyUserRestrictions(eq(UserHandle.USER_SYSTEM),
7959                                 MockUtils.checkUserRestrictions(globalRestrictions),
7960                                 MockUtils.checkUserRestrictions(
7961                                         UserHandle.USER_SYSTEM, localRestrictions),
7962                                 eq(true));
7963                 reset(getServices().userManagerInternal);
7964 
7965                 DpmTestUtils.assertRestrictions(DpmTestUtils.newRestrictions(restriction),
7966                         dpm.getUserRestrictions(admin1));
7967 
7968                 dpm.clearUserRestriction(admin1, restriction);
7969                 reset(getServices().userManagerInternal);
7970             }
7971         }
7972     }
7973 
7974     @Test
7975     @FlakyTest(bugId = 260145949)
testSetLockTaskFeatures_financeDo_validLockTaskFeatures_lockTaskFeaturesSet()7976     public void testSetLockTaskFeatures_financeDo_validLockTaskFeatures_lockTaskFeaturesSet()
7977             throws Exception {
7978         int validLockTaskFeatures = LOCK_TASK_FEATURE_SYSTEM_INFO | LOCK_TASK_FEATURE_KEYGUARD
7979                 | LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_GLOBAL_ACTIONS
7980                 | LOCK_TASK_FEATURE_NOTIFICATIONS | LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
7981         setDeviceOwner();
7982         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
7983 
7984         dpm.setLockTaskFeatures(admin1, validLockTaskFeatures);
7985 
7986         verify(getServices().iactivityTaskManager)
7987                 .updateLockTaskFeatures(eq(UserHandle.USER_SYSTEM), eq(validLockTaskFeatures));
7988     }
7989 
7990     @Test
7991     @FlakyTest(bugId = 260145949)
testSetLockTaskFeatures_financeDo_invalidLockTaskFeatures_throwsException()7992     public void testSetLockTaskFeatures_financeDo_invalidLockTaskFeatures_throwsException()
7993             throws Exception {
7994         int invalidLockTaskFeatures = LOCK_TASK_FEATURE_NONE | LOCK_TASK_FEATURE_OVERVIEW
7995                 | LOCK_TASK_FEATURE_HOME;
7996         setDeviceOwner();
7997         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
7998         // Called during setup.
7999         verify(getServices().iactivityTaskManager).updateLockTaskFeatures(anyInt(), anyInt());
8000 
8001         assertExpectException(SecurityException.class, /* messageRegex= */ null,
8002                 () -> dpm.setLockTaskFeatures(admin1, invalidLockTaskFeatures));
8003 
8004         verifyNoMoreInteractions(getServices().iactivityTaskManager);
8005     }
8006 
8007     @Test
8008     @FlakyTest(bugId = 260145949)
testIsUninstallBlocked_financeDo_success()8009     public void testIsUninstallBlocked_financeDo_success() throws Exception {
8010         String packageName = "com.android.foo.package";
8011         setDeviceOwner();
8012         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8013         when(getServices().ipackageManager.getBlockUninstallForUser(
8014                 eq(packageName), eq(UserHandle.getCallingUserId())))
8015                 .thenReturn(true);
8016 
8017         assertThat(dpm.isUninstallBlocked(admin1, packageName)).isTrue();
8018     }
8019 
8020     @Test
8021     @Ignore("b/277916462")
testSetUninstallBlocked_financeDo_success()8022     public void testSetUninstallBlocked_financeDo_success() throws Exception {
8023         String packageName = "com.android.foo.package";
8024         setDeviceOwner();
8025         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8026 
8027         dpm.setUninstallBlocked(admin1, packageName, false);
8028 
8029         verify(getServices().ipackageManager)
8030                 .setBlockUninstallForUser(eq(packageName), eq(false),
8031                         eq(UserHandle.USER_SYSTEM));
8032     }
8033 
8034     @Test
8035     @Ignore("b/277916462")
testSetUserControlDisabledPackages_financeDo_success()8036     public void testSetUserControlDisabledPackages_financeDo_success() throws Exception {
8037         List<String> packages = new ArrayList<>();
8038         packages.add("com.android.foo.package");
8039         setDeviceOwner();
8040         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8041 
8042         dpm.setUserControlDisabledPackages(admin1, packages);
8043 
8044         verify(getServices().packageManagerInternal)
8045                 .setOwnerProtectedPackages(eq(UserHandle.USER_ALL), eq(packages));
8046     }
8047 
8048     @Test
testGetUserControlDisabledPackages_financeDo_success()8049     public void testGetUserControlDisabledPackages_financeDo_success() throws Exception {
8050         setDeviceOwner();
8051         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8052 
8053         assertThat(dpm.getUserControlDisabledPackages(admin1)).isEmpty();
8054     }
8055 
8056     @Test
testSetOrganizationName_financeDo_success()8057     public void testSetOrganizationName_financeDo_success() throws Exception {
8058         String organizationName = "Test Organization";
8059         setDeviceOwner();
8060         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8061 
8062         dpm.setOrganizationName(admin1, organizationName);
8063 
8064         assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo(organizationName);
8065     }
8066 
8067     @Test
testSetShortSupportMessage_financeDo_success()8068     public void testSetShortSupportMessage_financeDo_success() throws Exception {
8069         String supportMessage = "Test short support message";
8070         setDeviceOwner();
8071         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8072 
8073         dpm.setShortSupportMessage(admin1, supportMessage);
8074 
8075         assertThat(dpm.getShortSupportMessage(admin1)).isEqualTo(supportMessage);
8076     }
8077 
8078     @Test
testIsBackupServiceEnabled_financeDo_success()8079     public void testIsBackupServiceEnabled_financeDo_success() throws Exception {
8080         setDeviceOwner();
8081         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8082         when(getServices().ibackupManager.isBackupServiceActive(eq(UserHandle.USER_SYSTEM)))
8083                 .thenReturn(true);
8084 
8085         assertThat(dpm.isBackupServiceEnabled(admin1)).isTrue();
8086     }
8087 
8088     @Test
testSetBackupServiceEnabled_financeDo_success()8089     public void testSetBackupServiceEnabled_financeDo_success() throws Exception {
8090         setDeviceOwner();
8091         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8092 
8093         dpm.setBackupServiceEnabled(admin1, true);
8094 
8095         verify(getServices().ibackupManager)
8096                 .setBackupServiceActive(eq(UserHandle.USER_SYSTEM), eq(true));
8097     }
8098 
8099     @Test
testIsLockTaskPermitted_financeDo_success()8100     public void testIsLockTaskPermitted_financeDo_success() throws Exception {
8101         String packageName = "com.android.foo.package";
8102         mockPolicyExemptApps(packageName);
8103         mockVendorPolicyExemptApps();
8104         setDeviceOwner();
8105         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8106 
8107         assertThat(dpm.isLockTaskPermitted(packageName)).isTrue();
8108     }
8109 
8110     @Test
8111     @FlakyTest(bugId = 260145949)
testSetLockTaskPackages_financeDo_success()8112     public void testSetLockTaskPackages_financeDo_success() throws Exception {
8113         String[] packages = {"com.android.foo.package"};
8114         mockEmptyPolicyExemptApps();
8115         setDeviceOwner();
8116         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8117 
8118         dpm.setLockTaskPackages(admin1, packages);
8119 
8120         verify(getServices().iactivityManager)
8121                 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(packages));
8122     }
8123 
8124     @Test
8125     @Ignore("b/277916462")
testAddPersistentPreferredActivity_financeDo_success()8126     public void testAddPersistentPreferredActivity_financeDo_success() throws Exception {
8127         IntentFilter filter = new IntentFilter();
8128         ComponentName target = new ComponentName(admin2.getPackageName(), "test.class");
8129         setDeviceOwner();
8130         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8131 
8132         dpm.addPersistentPreferredActivity(admin1, filter, target);
8133 
8134         verify(getServices().ipackageManager)
8135                 .addPersistentPreferredActivity(eq(filter), eq(target), eq(UserHandle.USER_SYSTEM));
8136         verify(getServices().ipackageManager)
8137                 .flushPackageRestrictionsAsUser(eq(UserHandle.USER_SYSTEM));
8138     }
8139 
8140     @Test
8141     @Ignore("b/277916462")
testClearPackagePersistentPreferredActvities_financeDo_success()8142     public void testClearPackagePersistentPreferredActvities_financeDo_success() throws Exception {
8143         String packageName = admin2.getPackageName();
8144         setDeviceOwner();
8145         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8146 
8147         dpm.clearPackagePersistentPreferredActivities(admin1, packageName);
8148 
8149         verify(getServices().ipackageManager)
8150                 .clearPackagePersistentPreferredActivities(
8151                         eq(packageName), eq(UserHandle.USER_SYSTEM));
8152         verify(getServices().ipackageManager)
8153                 .flushPackageRestrictionsAsUser(eq(UserHandle.USER_SYSTEM));
8154     }
8155 
8156     @Test
testWipeDevice_financeDo_success()8157     public void testWipeDevice_financeDo_success() throws Exception {
8158         setDeviceOwner();
8159         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8160         when(getServices().userManager.getUserRestrictionSource(
8161                 UserManager.DISALLOW_FACTORY_RESET,
8162                 UserHandle.SYSTEM))
8163                 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
8164         when(mMockContext.getResources()
8165                 .getString(R.string.work_profile_deleted_description_dpm_wipe))
8166                 .thenReturn("Test string");
8167 
8168         dpm.wipeDevice(0);
8169 
8170         verifyRebootWipeUserData(/* wipeEuicc= */ false);
8171     }
8172 
8173     @Test
testIsDeviceOwnerApp_financeDo_success()8174     public void testIsDeviceOwnerApp_financeDo_success() throws Exception {
8175         setDeviceOwner();
8176         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8177 
8178         assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue();
8179     }
8180 
8181     @Test
testClearDeviceOwnerApp_financeDo_success()8182     public void testClearDeviceOwnerApp_financeDo_success() throws Exception {
8183         setDeviceOwner();
8184         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8185 
8186         dpm.clearDeviceOwnerApp(admin1.getPackageName());
8187 
8188         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isNull();
8189         assertThat(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)).isFalse();
8190         verify(mMockContext.spiedContext, times(2))
8191                 .sendBroadcastAsUser(
8192                         MockUtils.checkIntentAction(
8193                                 DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
8194                         eq(UserHandle.SYSTEM));
8195     }
8196 
8197     @Test
testSetPermissionGrantState_financeDo_notReadPhoneStatePermission_throwsException()8198     public void testSetPermissionGrantState_financeDo_notReadPhoneStatePermission_throwsException()
8199             throws Exception {
8200         setDeviceOwner();
8201         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8202 
8203         assertExpectException(SecurityException.class, /* messageRegex= */ null,
8204                 () -> dpm.setPermissionGrantState(admin1, admin1.getPackageName(),
8205                         permission.READ_CALENDAR,
8206                         DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED));
8207     }
8208 
8209     @Test
testSetPermissionGrantState_financeDo_grantPermissionToNonDeviceOwnerPackage_throwsException()8210     public void testSetPermissionGrantState_financeDo_grantPermissionToNonDeviceOwnerPackage_throwsException()
8211             throws Exception {
8212         setDeviceOwner();
8213         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8214 
8215         assertExpectException(SecurityException.class, /* messageRegex= */ null,
8216                 () -> dpm.setPermissionGrantState(admin1, "com.android.foo.package",
8217                         permission.READ_PHONE_STATE,
8218                         DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED));
8219     }
8220 
8221     @Test
testGetPermissionGrantState_financeDo_notReadPhoneStatePermission_throwsException()8222     public void testGetPermissionGrantState_financeDo_notReadPhoneStatePermission_throwsException()
8223             throws Exception {
8224         setDeviceOwner();
8225         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8226 
8227         assertExpectException(SecurityException.class, /* messageRegex= */ null,
8228                 () -> dpm.getPermissionGrantState(admin1, admin1.getPackageName(),
8229                         permission.READ_CALENDAR));
8230     }
8231 
8232     @Test
testGetPermissionGrantState_financeDo_notDeviceOwnerPackage_throwsException()8233     public void testGetPermissionGrantState_financeDo_notDeviceOwnerPackage_throwsException()
8234             throws Exception {
8235         setDeviceOwner();
8236         dpm.setDeviceOwnerType(admin1, DEVICE_OWNER_TYPE_FINANCED);
8237 
8238         assertExpectException(SecurityException.class, /* messageRegex= */ null,
8239                 () -> dpm.getPermissionGrantState(admin1, "com.android.foo.package",
8240                         permission.READ_PHONE_STATE));
8241     }
8242 
8243     @Test
testSetUsbDataSignalingEnabled_noDeviceOwnerOrPoOfOrgOwnedDevice()8244     public void testSetUsbDataSignalingEnabled_noDeviceOwnerOrPoOfOrgOwnedDevice() {
8245         assertThrows(SecurityException.class,
8246                 () -> dpm.setUsbDataSignalingEnabled(true));
8247     }
8248 
8249     @Test
testSetUsbDataSignalingEnabled_asDeviceOwner()8250     public void testSetUsbDataSignalingEnabled_asDeviceOwner() throws Exception {
8251         setDeviceOwner();
8252         when(getServices().usbManager.enableUsbDataSignal(false)).thenReturn(true);
8253         when(getServices().usbManager.getUsbHalVersion()).thenReturn(UsbManager.USB_HAL_V1_3);
8254 
8255         assertThat(dpm.isUsbDataSignalingEnabled()).isTrue();
8256 
8257         dpm.setUsbDataSignalingEnabled(false);
8258 
8259         assertThat(dpm.isUsbDataSignalingEnabled()).isFalse();
8260     }
8261 
8262     @Test
testIsUsbDataSignalingEnabledForUser()8263     public void testIsUsbDataSignalingEnabledForUser() throws Exception {
8264         when(getServices().usbManager.enableUsbDataSignal(false)).thenReturn(true);
8265         when(getServices().usbManager.getUsbHalVersion()).thenReturn(UsbManager.USB_HAL_V1_3);
8266         setDeviceOwner();
8267         dpm.setUsbDataSignalingEnabled(false);
8268 
8269         assertThat(dpm.isUsbDataSignalingEnabled()).isFalse();
8270     }
8271 
8272     @Test
testSetUsbDataSignalingEnabled_asPoOfOrgOwnedDevice()8273     public void testSetUsbDataSignalingEnabled_asPoOfOrgOwnedDevice() throws Exception {
8274         final int managedProfileUserId = 15;
8275         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
8276         addManagedProfile(admin1, managedProfileAdminUid, admin1);
8277         configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
8278         mContext.binder.callingUid = managedProfileAdminUid;
8279         when(getServices().usbManager.enableUsbDataSignal(false)).thenReturn(true);
8280         when(getServices().usbManager.getUsbHalVersion()).thenReturn(UsbManager.USB_HAL_V1_3);
8281 
8282         assertThat(dpm.isUsbDataSignalingEnabled()).isTrue();
8283 
8284         dpm.setUsbDataSignalingEnabled(false);
8285 
8286         assertThat(dpm.isUsbDataSignalingEnabled()).isFalse();
8287     }
8288 
8289     @Test
testCanUsbDataSignalingBeDisabled_canBeDisabled()8290     public void testCanUsbDataSignalingBeDisabled_canBeDisabled() throws Exception {
8291         when(getServices().usbManager.getUsbHalVersion()).thenReturn(UsbManager.USB_HAL_V1_3);
8292 
8293         assertThat(dpm.canUsbDataSignalingBeDisabled()).isTrue();
8294     }
8295 
8296     @Test
testCanUsbDataSignalingBeDisabled_cannotBeDisabled()8297     public void testCanUsbDataSignalingBeDisabled_cannotBeDisabled() throws Exception {
8298         setDeviceOwner();
8299         when(getServices().usbManager.getUsbHalVersion()).thenReturn(UsbManager.USB_HAL_V1_2);
8300 
8301         assertThat(dpm.canUsbDataSignalingBeDisabled()).isFalse();
8302         assertThrows(IllegalStateException.class,
8303                 () -> dpm.setUsbDataSignalingEnabled(true));
8304     }
8305 
8306     @Test
testSetUsbDataSignalingEnabled_noChangeToActiveAdmin()8307     public void testSetUsbDataSignalingEnabled_noChangeToActiveAdmin()
8308             throws Exception {
8309         setDeviceOwner();
8310         when(getServices().usbManager.getUsbHalVersion()).thenReturn(UsbManager.USB_HAL_V1_3);
8311         boolean enabled = dpm.isUsbDataSignalingEnabled();
8312 
8313         dpm.setUsbDataSignalingEnabled(true);
8314 
8315         assertThat(dpm.isUsbDataSignalingEnabled()).isEqualTo(enabled);
8316     }
8317 
8318     @Test
testGetPolicyExemptApps_noPermission()8319     public void testGetPolicyExemptApps_noPermission() {
8320         assertThrows(SecurityException.class, () -> dpm.getPolicyExemptApps());
8321     }
8322 
8323     @Test
testGetPolicyExemptApps_empty()8324     public void testGetPolicyExemptApps_empty() {
8325         grantManageDeviceAdmins();
8326         mockPolicyExemptApps();
8327         mockVendorPolicyExemptApps();
8328 
8329         assertThat(dpm.getPolicyExemptApps()).isEmpty();
8330     }
8331 
8332     @Test
testGetPolicyExemptApps_baseOnly()8333     public void testGetPolicyExemptApps_baseOnly() {
8334         grantManageDeviceAdmins();
8335         mockPolicyExemptApps("foo");
8336         mockVendorPolicyExemptApps();
8337 
8338         assertThat(dpm.getPolicyExemptApps()).containsExactly("foo");
8339     }
8340 
8341     @Test
testGetPolicyExemptApps_vendorOnly()8342     public void testGetPolicyExemptApps_vendorOnly() {
8343         grantManageDeviceAdmins();
8344         mockPolicyExemptApps();
8345         mockVendorPolicyExemptApps("bar");
8346 
8347         assertThat(dpm.getPolicyExemptApps()).containsExactly("bar");
8348     }
8349 
8350     @Test
testGetPolicyExemptApps_baseAndVendor()8351     public void testGetPolicyExemptApps_baseAndVendor() {
8352         grantManageDeviceAdmins();
8353         mockPolicyExemptApps("4", "23", "15", "42", "8");
8354         mockVendorPolicyExemptApps("16", "15", "4");
8355 
8356         assertThat(dpm.getPolicyExemptApps()).containsExactly("4", "8", "15", "16", "23", "42");
8357     }
8358 
8359     @Test
testSetGlobalPrivateDnsModeOpportunistic_asDeviceOwner()8360     public void testSetGlobalPrivateDnsModeOpportunistic_asDeviceOwner() throws Exception {
8361         setDeviceOwner();
8362         // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
8363         // feature is disabled because there are non-affiliated secondary users.
8364         getServices().removeUser(CALLER_USER_HANDLE);
8365         clearInvocations(getServices().settings);
8366 
8367         int result = dpm.setGlobalPrivateDnsModeOpportunistic(admin1);
8368 
8369         assertThat(result).isEqualTo(PRIVATE_DNS_SET_NO_ERROR);
8370     }
8371 
8372     @Test
testSetGlobalPrivateDnsModeOpportunistic_hasUnaffiliatedUsers()8373     public void testSetGlobalPrivateDnsModeOpportunistic_hasUnaffiliatedUsers() throws Exception {
8374         setDeviceOwner();
8375         setAsProfileOwner(admin2);
8376 
8377         assertThrows(SecurityException.class,
8378                 () -> dpm.setGlobalPrivateDnsModeOpportunistic(admin1));
8379     }
8380 
8381     @Test
testSetRecommendedGlobalProxy_asDeviceOwner()8382     public void testSetRecommendedGlobalProxy_asDeviceOwner() throws Exception {
8383         setDeviceOwner();
8384         // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
8385         // feature is disabled because there are non-affiliated secondary users.
8386         getServices().removeUser(CALLER_USER_HANDLE);
8387 
8388         dpm.setRecommendedGlobalProxy(admin1, null);
8389 
8390         verify(getServices().connectivityManager).setGlobalProxy(null);
8391     }
8392 
8393     @Test
testSetRecommendedGlobalProxy_hasUnaffiliatedUsers()8394     public void testSetRecommendedGlobalProxy_hasUnaffiliatedUsers() throws Exception {
8395         setDeviceOwner();
8396         setAsProfileOwner(admin2);
8397 
8398         assertThrows(SecurityException.class, () -> dpm.setRecommendedGlobalProxy(admin1, null));
8399     }
8400 
8401     @Test
testSetAlwaysOnVpnPackage_clearsAdminVpn()8402     public void testSetAlwaysOnVpnPackage_clearsAdminVpn() throws Exception {
8403         setDeviceOwner();
8404 
8405         when(getServices().vpnManager
8406                 .setAlwaysOnVpnPackageForUser(anyInt(), any(), anyBoolean(), any()))
8407                 .thenReturn(true);
8408 
8409         // Set VPN package to admin package.
8410         dpm.setAlwaysOnVpnPackage(admin1, admin1.getPackageName(), false, null);
8411 
8412         verify(getServices().vpnManager).setAlwaysOnVpnPackageForUser(
8413                 UserHandle.USER_SYSTEM, admin1.getPackageName(), false, null);
8414 
8415         // Clear VPN package.
8416         dpm.setAlwaysOnVpnPackage(admin1, null, false, null);
8417 
8418         // Change should be propagated to VpnManager
8419         verify(getServices().vpnManager).setAlwaysOnVpnPackageForUser(
8420                 UserHandle.USER_SYSTEM, null, false, null);
8421         // The package should lose authorization to start VPN.
8422         verify(getServices().appOpsManager).setMode(OP_ACTIVATE_VPN,
8423                 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1.getPackageName(), MODE_DEFAULT);
8424     }
8425 
8426     @Test
testSetAlwaysOnVpnPackage_doesntKillUserVpn()8427     public void testSetAlwaysOnVpnPackage_doesntKillUserVpn() throws Exception {
8428         setDeviceOwner();
8429 
8430         when(getServices().vpnManager
8431                 .setAlwaysOnVpnPackageForUser(anyInt(), any(), anyBoolean(), any()))
8432                 .thenReturn(true);
8433 
8434         // this time it shouldn't go into VpnManager anymore.
8435         dpm.setAlwaysOnVpnPackage(admin1, null, false, null);
8436 
8437         verifyNoMoreInteractions(getServices().vpnManager);
8438         verifyNoMoreInteractions(getServices().appOpsManager);
8439     }
8440 
8441     @Test
testDisallowConfigVpn_clearsUserVpn()8442     public void testDisallowConfigVpn_clearsUserVpn() throws Exception {
8443         final String userVpnPackage = "org.some.vpn.servcie";
8444         final int userVpnUid = 20374;
8445 
8446         setDeviceOwner();
8447 
8448         setupVpnAuthorization(userVpnPackage, userVpnUid);
8449 
8450         simulateRestrictionAdded(UserManager.DISALLOW_CONFIG_VPN);
8451 
8452         verify(getServices().vpnManager).setAlwaysOnVpnPackageForUser(
8453                 UserHandle.USER_SYSTEM, null, false, null);
8454         verify(getServices().appOpsManager).setMode(OP_ACTIVATE_VPN,
8455                 userVpnUid, userVpnPackage, MODE_DEFAULT);
8456     }
8457 
8458     @Test
testDisallowConfigVpn_doesntKillAdminVpn()8459     public void testDisallowConfigVpn_doesntKillAdminVpn() throws Exception {
8460         setDeviceOwner();
8461 
8462         when(getServices().vpnManager
8463                 .setAlwaysOnVpnPackageForUser(anyInt(), any(), anyBoolean(), any()))
8464                 .thenReturn(true);
8465 
8466         // Set VPN package to admin package.
8467         dpm.setAlwaysOnVpnPackage(admin1, admin1.getPackageName(), false, null);
8468         setupVpnAuthorization(admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID);
8469         clearInvocations(getServices().vpnManager);
8470 
8471         simulateRestrictionAdded(UserManager.DISALLOW_CONFIG_VPN);
8472 
8473         // Admin-set package should remain always-on and should retain its authorization.
8474         verifyNoMoreInteractions(getServices().vpnManager);
8475         verify(getServices().appOpsManager, never()).setMode(OP_ACTIVATE_VPN,
8476                 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1.getPackageName(), MODE_DEFAULT);
8477     }
8478 
8479     @Test
testGetOrganizationNameForUser_calledByNonPrivilegedApp_throwsException()8480     public void testGetOrganizationNameForUser_calledByNonPrivilegedApp_throwsException() {
8481         assertExpectException(SecurityException.class, "Calling identity is not authorized",
8482                 () -> dpm.getOrganizationNameForUser(UserHandle.USER_SYSTEM));
8483     }
8484 
8485     @Test
testSetWifiMinimumSecurity_noDeviceOwnerOrPoOfOrgOwnedDevice()8486     public void testSetWifiMinimumSecurity_noDeviceOwnerOrPoOfOrgOwnedDevice() {
8487         assertThrows(SecurityException.class, () -> dpm.setMinimumRequiredWifiSecurityLevel(
8488                 DevicePolicyManager.WIFI_SECURITY_PERSONAL));
8489     }
8490 
8491     @Test
testSetWifiMinimumSecurity_asDeviceOwner()8492     public void testSetWifiMinimumSecurity_asDeviceOwner() throws Exception {
8493         setDeviceOwner();
8494 
8495         final Set<Integer> allowedLevels = Set.of(WIFI_SECURITY_OPEN, WIFI_SECURITY_PERSONAL,
8496                 WIFI_SECURITY_ENTERPRISE_EAP, WIFI_SECURITY_ENTERPRISE_192);
8497         for (int level : allowedLevels) {
8498             dpm.setMinimumRequiredWifiSecurityLevel(level);
8499             assertThat(dpm.getMinimumRequiredWifiSecurityLevel()).isEqualTo(level);
8500         }
8501     }
8502 
8503     @Test
testSetWifiMinimumSecurity_asPoOfOrgOwnedDevice()8504     public void testSetWifiMinimumSecurity_asPoOfOrgOwnedDevice() throws Exception {
8505         final int managedProfileUserId = 15;
8506         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
8507         addManagedProfile(admin1, managedProfileAdminUid, admin1);
8508         configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
8509         mContext.binder.callingUid = managedProfileAdminUid;
8510 
8511         final Set<Integer> allowedLevels = Set.of(WIFI_SECURITY_OPEN, WIFI_SECURITY_PERSONAL,
8512                 WIFI_SECURITY_ENTERPRISE_EAP, WIFI_SECURITY_ENTERPRISE_192);
8513         for (int level : allowedLevels) {
8514             dpm.setMinimumRequiredWifiSecurityLevel(level);
8515             assertThat(dpm.getMinimumRequiredWifiSecurityLevel()).isEqualTo(level);
8516         }
8517     }
8518 
8519     @Test
testSetSsidAllowlist_noDeviceOwnerOrPoOfOrgOwnedDevice()8520     public void testSetSsidAllowlist_noDeviceOwnerOrPoOfOrgOwnedDevice() {
8521         final Set<WifiSsid> ssids = new ArraySet<>(
8522                 Arrays.asList(WifiSsid.fromBytes("ssid1".getBytes(StandardCharsets.UTF_8))));
8523         WifiSsidPolicy policy = new WifiSsidPolicy(
8524                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, ssids);
8525         assertThrows(SecurityException.class, () -> dpm.setWifiSsidPolicy(policy));
8526     }
8527 
8528     @Test
testSetSsidAllowlist_asDeviceOwner()8529     public void testSetSsidAllowlist_asDeviceOwner() throws Exception {
8530         setDeviceOwner();
8531 
8532         final Set<WifiSsid> ssids = new ArraySet<>(
8533                 Arrays.asList(WifiSsid.fromBytes("ssid1".getBytes(StandardCharsets.UTF_8))));
8534         WifiSsidPolicy policy = new WifiSsidPolicy(
8535                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, ssids);
8536         dpm.setWifiSsidPolicy(policy);
8537         assertThat(dpm.getWifiSsidPolicy().getSsids()).isEqualTo(ssids);
8538         assertThat(dpm.getWifiSsidPolicy().getPolicyType()).isEqualTo(
8539                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST);
8540     }
8541 
8542     @Test
testSetSsidAllowlist_asPoOfOrgOwnedDevice()8543     public void testSetSsidAllowlist_asPoOfOrgOwnedDevice() throws Exception {
8544         final int managedProfileUserId = 15;
8545         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
8546         addManagedProfile(admin1, managedProfileAdminUid, admin1);
8547         configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
8548         mContext.binder.callingUid = managedProfileAdminUid;
8549 
8550         final Set<WifiSsid> ssids = new ArraySet<>(
8551                 Arrays.asList(WifiSsid.fromBytes("ssid1".getBytes(StandardCharsets.UTF_8)),
8552                         WifiSsid.fromBytes("ssid2".getBytes(StandardCharsets.UTF_8)),
8553                         WifiSsid.fromBytes("ssid3".getBytes(StandardCharsets.UTF_8))));
8554         WifiSsidPolicy policy = new WifiSsidPolicy(
8555                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, ssids);
8556         dpm.setWifiSsidPolicy(policy);
8557         assertThat(dpm.getWifiSsidPolicy().getSsids()).isEqualTo(ssids);
8558         assertThat(dpm.getWifiSsidPolicy().getPolicyType()).isEqualTo(
8559                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST);
8560     }
8561 
8562     @Test
testSetSsidAllowlist_emptyList()8563     public void testSetSsidAllowlist_emptyList() throws Exception {
8564         setDeviceOwner();
8565 
8566         final Set<WifiSsid> ssids = new ArraySet<>();
8567         assertThrows(IllegalArgumentException.class,
8568                 () -> new WifiSsidPolicy(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, ssids));
8569     }
8570 
8571     @Test
testSetSsidDenylist_noDeviceOwnerOrPoOfOrgOwnedDevice()8572     public void testSetSsidDenylist_noDeviceOwnerOrPoOfOrgOwnedDevice() {
8573         final Set<WifiSsid> ssids = new ArraySet<>(
8574                 Arrays.asList(WifiSsid.fromBytes("ssid1".getBytes(StandardCharsets.UTF_8))));
8575         WifiSsidPolicy policy = new WifiSsidPolicy(
8576                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, ssids);
8577         assertThrows(SecurityException.class, () -> dpm.setWifiSsidPolicy(policy));
8578     }
8579 
8580     @Test
testSetSsidDenylist_asDeviceOwner()8581     public void testSetSsidDenylist_asDeviceOwner() throws Exception {
8582         setDeviceOwner();
8583 
8584         final Set<WifiSsid> ssids = new ArraySet<>(
8585                 Arrays.asList(WifiSsid.fromBytes("ssid1".getBytes(StandardCharsets.UTF_8))));
8586         WifiSsidPolicy policy = new WifiSsidPolicy(
8587                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, ssids);
8588         dpm.setWifiSsidPolicy(policy);
8589         assertThat(dpm.getWifiSsidPolicy().getSsids()).isEqualTo(ssids);
8590         assertThat(dpm.getWifiSsidPolicy().getPolicyType()).isEqualTo(
8591                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST);
8592     }
8593 
8594     @Test
testSetSsidDenylist_asPoOfOrgOwnedDevice()8595     public void testSetSsidDenylist_asPoOfOrgOwnedDevice() throws Exception {
8596         final int managedProfileUserId = 15;
8597         final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
8598         addManagedProfile(admin1, managedProfileAdminUid, admin1);
8599         configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
8600         mContext.binder.callingUid = managedProfileAdminUid;
8601 
8602         final Set<WifiSsid> ssids = new ArraySet<>(
8603                 Arrays.asList(WifiSsid.fromBytes("ssid1".getBytes(StandardCharsets.UTF_8)),
8604                         WifiSsid.fromBytes("ssid2".getBytes(StandardCharsets.UTF_8)),
8605                         WifiSsid.fromBytes("ssid3".getBytes(StandardCharsets.UTF_8))));
8606         WifiSsidPolicy policy = new WifiSsidPolicy(
8607                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, ssids);
8608         dpm.setWifiSsidPolicy(policy);
8609         assertThat(dpm.getWifiSsidPolicy().getSsids()).isEqualTo(ssids);
8610         assertThat(dpm.getWifiSsidPolicy().getPolicyType()).isEqualTo(
8611                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST);
8612     }
8613 
8614     @Test
testSetSsidDenylist_emptyList()8615     public void testSetSsidDenylist_emptyList() throws Exception {
8616         setDeviceOwner();
8617 
8618         final Set<WifiSsid> ssids = new ArraySet<>();
8619         assertThrows(IllegalArgumentException.class,
8620                 () -> new WifiSsidPolicy(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, ssids));
8621     }
8622 
8623     @Test
testSendLostModeLocationUpdate_noPermission()8624     public void testSendLostModeLocationUpdate_noPermission() {
8625         assertThrows(SecurityException.class, () -> dpm.sendLostModeLocationUpdate(
8626                 getServices().executor, /* empty callback */ result -> {}));
8627     }
8628 
8629     @Test
testSendLostModeLocationUpdate_notOrganizationOwnedDevice()8630     public void testSendLostModeLocationUpdate_notOrganizationOwnedDevice() {
8631         mContext.callerPermissions.add(permission.TRIGGER_LOST_MODE);
8632         assertThrows(IllegalStateException.class, () -> dpm.sendLostModeLocationUpdate(
8633                 getServices().executor, /* empty callback */ result -> {}));
8634     }
8635 
8636     @Test
testSendLostModeLocationUpdate_asDeviceOwner()8637     public void testSendLostModeLocationUpdate_asDeviceOwner() throws Exception {
8638         mContext.callerPermissions.add(permission.TRIGGER_LOST_MODE);
8639         setDeviceOwner();
8640         when(getServices().locationManager.isProviderEnabled(FUSED_PROVIDER)).thenReturn(true);
8641 
8642         dpm.sendLostModeLocationUpdate(getServices().executor, /* empty callback */ result -> {});
8643 
8644         verify(getServices().locationManager, times(1)).getCurrentLocation(
8645                 eq(FUSED_PROVIDER), any(), eq(getServices().executor), any());
8646     }
8647 
8648     @Test
testSendLostModeLocationUpdate_asProfileOwnerOfOrgOwnedDevice()8649     public void testSendLostModeLocationUpdate_asProfileOwnerOfOrgOwnedDevice() throws Exception {
8650         final int MANAGED_PROFILE_ADMIN_UID =
8651                 UserHandle.getUid(CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
8652         mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
8653         mContext.callerPermissions.add(permission.TRIGGER_LOST_MODE);
8654         addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
8655         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
8656         when(getServices().locationManager.isProviderEnabled(FUSED_PROVIDER)).thenReturn(true);
8657 
8658         dpm.sendLostModeLocationUpdate(getServices().executor, /* empty callback */ result -> {});
8659 
8660         verify(getServices().locationManager, times(1)).getCurrentLocation(
8661                 eq(FUSED_PROVIDER), any(), eq(getServices().executor), any());
8662     }
8663 
8664     @Test
testSendLostModeLocationUpdate_noProviderIsEnabled()8665     public void testSendLostModeLocationUpdate_noProviderIsEnabled() throws Exception {
8666         mContext.callerPermissions.add(permission.TRIGGER_LOST_MODE);
8667         setDeviceOwner();
8668         when(getServices().locationManager.isProviderEnabled(FUSED_PROVIDER)).thenReturn(false);
8669         when(getServices().locationManager.isProviderEnabled(NETWORK_PROVIDER)).thenReturn(false);
8670         when(getServices().locationManager.isProviderEnabled(GPS_PROVIDER)).thenReturn(false);
8671 
8672         dpm.sendLostModeLocationUpdate(getServices().executor, /* empty callback */ result -> {});
8673 
8674         verify(getServices().locationManager, never()).getCurrentLocation(
8675                 eq(FUSED_PROVIDER), any(), eq(getServices().executor), any());
8676     }
8677 
8678     /**
8679      * Verifies that bundles with tons of moderately long strings are persisted correctly.
8680      *
8681      * Policy is serialized into binary XML and there is a limit on the max string length: 65535.
8682      * This test ensures that as long as each string in the trust agent configuration is below this
8683      * limit, the policy can be serialized and deserialized correctly, even when the total length
8684      * of the configuration is above that limit. This should be the case because PersistableBundle
8685      * contents are stored as XML subtrees rather than as strings.
8686      */
8687     @Test
testSetTrustAgentConfiguration_largeBundlePersisted()8688     public void testSetTrustAgentConfiguration_largeBundlePersisted() {
8689         setAsProfileOwner(admin1);
8690 
8691         ComponentName agent = new ComponentName("some.trust.agent", "some.trust.agent.Agent");
8692         PersistableBundle configIn = new PersistableBundle();
8693         String kilobyteString = new String(new char[1024]).replace('\0', 'A');
8694         for (int i = 0; i < 1024; i++) {
8695             configIn.putString("key-" + i, kilobyteString);
8696         }
8697 
8698         runAsCaller(mAdmin1Context, dpms, dpm -> {
8699             dpm.setTrustAgentConfiguration(admin1, agent, configIn);
8700         });
8701 
8702         // Re-read policies to see if they were serialized/deserialized correctly.
8703         initializeDpms();
8704 
8705         List<PersistableBundle> configsOut = new ArrayList<>();
8706         runAsCaller(mAdmin1Context, dpms, dpm -> {
8707             configsOut.addAll(dpm.getTrustAgentConfiguration(admin1, agent));
8708         });
8709 
8710         assertThat(configsOut.size()).isEqualTo(1);
8711         PersistableBundle configOut = configsOut.get(0);
8712         assertThat(configOut.size()).isEqualTo(1024);
8713         for (int i = 0; i < 1024; i++) {
8714             assertThat(configOut.getString("key-" + i, null)).isEqualTo(kilobyteString);
8715         }
8716     }
8717 
8718     @RequiresFlagsEnabled(Flags.FLAG_REMOVE_MANAGED_ESIM_ON_WORK_PROFILE_DELETION)
8719     @Test
testManagedProfileDeleted_managedEmbeddedSubscriptionDeleted()8720     public void testManagedProfileDeleted_managedEmbeddedSubscriptionDeleted() throws Exception {
8721         // Setup PO mode.
8722         setupProfileOwner();
8723         // Mock SubscriptionManager to return a subscription managed by the profile owner package.
8724         int managedSubscriptionId = 42;
8725         SubscriptionInfo managedSubscription = new SubscriptionInfo.Builder().setCardId(1).setId(
8726                 managedSubscriptionId).setGroupOwner(admin1.getPackageName()).build();
8727         when(getServices().subscriptionManager.getAvailableSubscriptionInfoList()).thenReturn(
8728                 List.of(managedSubscription));
8729 
8730         // Send a ACTION_MANAGED_PROFILE_REMOVED broadcast to emulate a managed profile being
8731         // removed.
8732         sendBroadcastWithUser(dpms, Intent.ACTION_MANAGED_PROFILE_REMOVED, CALLER_USER_HANDLE);
8733 
8734         // Verify that EuiccManager was called to delete the subscription.
8735         verify(getServices().euiccManager).deleteSubscription(eq(managedSubscriptionId), any());
8736     }
8737 
8738     @RequiresFlagsDisabled(Flags.FLAG_REMOVE_MANAGED_ESIM_ON_WORK_PROFILE_DELETION)
8739     @Test
testManagedProfileDeleted_flagDisabled_managedEmbeddedSubscriptionDeleted()8740     public void testManagedProfileDeleted_flagDisabled_managedEmbeddedSubscriptionDeleted()
8741             throws Exception {
8742         // Set up PO mode.
8743         setupProfileOwner();
8744         // Mock SubscriptionManager to return a subscription managed by the profile owner package.
8745         int managedSubscriptionId = 42;
8746         SubscriptionInfo managedSubscription = new SubscriptionInfo.Builder().setCardId(1).setId(
8747                 managedSubscriptionId).setGroupOwner(admin1.getPackageName()).build();
8748         when(getServices().subscriptionManager.getAvailableSubscriptionInfoList()).thenReturn(
8749                 List.of(managedSubscription));
8750 
8751         // Send a ACTION_MANAGED_PROFILE_REMOVED broadcast to emulate a managed profile being
8752         // removed.
8753         sendBroadcastWithUser(dpms, Intent.ACTION_MANAGED_PROFILE_REMOVED, CALLER_USER_HANDLE);
8754 
8755         // Verify that EuiccManager was not called to delete the subscription.
8756         verifyNoMoreInteractions(getServices().euiccManager);
8757     }
8758 
setupVpnAuthorization(String userVpnPackage, int userVpnUid)8759     private void setupVpnAuthorization(String userVpnPackage, int userVpnUid) {
8760         final AppOpsManager.PackageOps vpnOp = new AppOpsManager.PackageOps(userVpnPackage,
8761                 userVpnUid, List.of(new AppOpsManager.OpEntry(
8762                 OP_ACTIVATE_VPN, MODE_ALLOWED, Collections.emptyMap())));
8763         when(getServices().appOpsManager.getPackagesForOps(any(int[].class)))
8764                 .thenReturn(List.of(vpnOp));
8765     }
8766 
simulateRestrictionAdded(String restriction)8767     private void simulateRestrictionAdded(String restriction) {
8768         RestrictionsListener listener = new RestrictionsListener(
8769                 mServiceContext, getServices().userManagerInternal, dpms);
8770 
8771         final Bundle newRestrictions = new Bundle();
8772         newRestrictions.putBoolean(restriction, true);
8773         listener.onUserRestrictionsChanged(UserHandle.USER_SYSTEM, newRestrictions, new Bundle());
8774     }
8775 
setUserUnlocked(int userHandle, boolean unlocked)8776     private void setUserUnlocked(int userHandle, boolean unlocked) {
8777         when(getServices().userManager.isUserUnlocked(eq(userHandle))).thenReturn(unlocked);
8778         when(getServices().userManagerInternal.isUserUnlockingOrUnlocked(eq(userHandle)))
8779                 .thenReturn(unlocked);
8780     }
8781 
prepareMocksForSetMaximumProfileTimeOff()8782     private void prepareMocksForSetMaximumProfileTimeOff() throws Exception {
8783         addManagedProfile(admin1, DpmMockContext.CALLER_UID, admin1);
8784         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
8785 
8786         when(getServices().userManager.isUserUnlocked()).thenReturn(true);
8787 
8788         doReturn(Collections.singletonList(new ResolveInfo()))
8789                 .when(getServices().packageManager).queryIntentActivitiesAsUser(
8790                         any(Intent.class), anyInt(), eq(CALLER_USER_HANDLE));
8791 
8792         dpms.mMockInjector.setSystemCurrentTimeMillis(PROFILE_OFF_START);
8793         // To allow creation of Notification via Notification.Builder
8794         mContext.applicationInfo = mRealTestContext.getApplicationInfo();
8795 
8796         // Make locale available for date formatting:
8797         when(mServiceContext.resources.getConfiguration())
8798                 .thenReturn(mRealTestContext.getResources().getConfiguration());
8799 
8800         clearInvocations(getServices().ipackageManager);
8801     }
8802 
hasExtra(String... extras)8803     private static Matcher<Notification> hasExtra(String... extras) {
8804         assertWithMessage("Odd number of extra key-values").that(extras.length % 2).isEqualTo(0);
8805         return new BaseMatcher<Notification>() {
8806             @Override
8807             public boolean matches(Object item) {
8808                 final Notification notification = (Notification) item;
8809                 for (int i = 0; i < extras.length / 2; i++) {
8810                     if (!extras[i * 2 + 1].equals(notification.extras.getString(extras[i * 2]))) {
8811                         return false;
8812                     }
8813                 }
8814                 return true;
8815             }
8816             @Override
8817             public void describeTo(Description description) {
8818                 description.appendText("Notification{");
8819                 for (int i = 0; i < extras.length / 2; i++) {
8820                     if (i > 0) {
8821                         description.appendText(",");
8822                     }
8823                     description.appendText(extras[i * 2] + "=\"" + extras[i * 2 + 1] + "\"");
8824                 }
8825                 description.appendText("}");
8826             }
8827         };
8828     }
8829 
8830     // admin1 is the outgoing DPC, adminAnotherPackage is the incoming one.
8831     private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
8832         writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
8833                 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
8834 
8835         final long ident = mServiceContext.binder.clearCallingIdentity();
8836         setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
8837         setUpPackageManagerForFakeAdmin(adminAnotherPackage,
8838                 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
8839         // To simulate a reboot, we just reinitialize dpms and call systemReady
8840         initializeDpms();
8841 
8842         assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue();
8843         assertThat(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName())).isFalse();
8844         assertThat(dpm.isAdminActive(adminAnotherPackage)).isFalse();
8845         assertThat(dpm.isAdminActive(admin1)).isTrue();
8846         assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue();
8847         assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1);
8848 
8849         assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue();
8850         assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1);
8851         assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM);
8852         assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse();
8853 
8854         mServiceContext.binder.restoreCallingIdentity(ident);
8855     }
8856 
8857     // admin1 is the outgoing DPC, adminAnotherPackage is the incoming one.
8858     private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
8859         writeFakeTransferMetadataFile(CALLER_USER_HANDLE,
8860                 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
8861 
8862         int uid = UserHandle.getUid(CALLER_USER_HANDLE,
8863                 DpmMockContext.CALLER_SYSTEM_USER_UID);
8864         setUpPackageManagerForAdmin(admin1, uid);
8865         setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
8866         // To simulate a reboot, we just reinitialize dpms and call systemReady
8867         initializeDpms();
8868 
8869         assertThat(dpm.isProfileOwnerApp(admin1.getPackageName())).isTrue();
8870         assertThat(dpm.isAdminActive(admin1)).isTrue();
8871         assertThat(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName())).isFalse();
8872         assertThat(dpm.isAdminActive(adminAnotherPackage)).isFalse();
8873         assertThat(admin1).isEqualTo(dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE));
8874         assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse();
8875     }
8876 
8877     private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
8878         TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
8879         metadataManager.deleteMetadataFile();
8880 
8881         final TransferOwnershipMetadataManager.Metadata metadata =
8882                 new TransferOwnershipMetadataManager.Metadata(
8883                         admin1.flattenToString(), adminAnotherPackage.flattenToString(),
8884                         callerUserHandle,
8885                         adminType);
8886         metadataManager.saveMetadataFile(metadata);
8887     }
8888 
8889     private File getDeviceOwnerFile() {
8890         return dpms.mOwners.getDeviceOwnerFile();
8891     }
8892 
8893     private File getProfileOwnerFile() {
8894         return dpms.mOwners.getProfileOwnerFile(CALLER_USER_HANDLE);
8895     }
8896 
8897     private File getProfileOwnerPoliciesFile() {
8898         File parentDir = getServices().pathProvider.getUserSystemDirectory(CALLER_USER_HANDLE);
8899         return getPoliciesFile(parentDir);
8900     }
8901 
8902     private File getDeviceOwnerPoliciesFile() {
8903         return getPoliciesFile(getServices().systemUserDataDir);
8904     }
8905 
8906     private File getPoliciesFile(File parentDir) {
8907         return new File(parentDir, "device_policies.xml");
8908     }
8909 
8910     private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
8911         when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8912                 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
8913         dpms.notifyChangeToContentObserver(
8914                 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
8915     }
8916 
8917     private void assertProvisioningAllowed(String action, boolean expected) {
8918         assertWithMessage("isProvisioningAllowed(%s) returning unexpected result", action)
8919                 .that(dpm.isProvisioningAllowed(action)).isEqualTo(expected);
8920     }
8921 
8922     private void assertProvisioningAllowed(String action, boolean expected, String packageName,
8923             int uid) {
8924         final String previousPackageName = mContext.packageName;
8925         final int previousUid = mMockContext.binder.callingUid;
8926 
8927         // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
8928         mContext.packageName = packageName;
8929         mMockContext.binder.callingUid = uid;
8930         assertProvisioningAllowed(action, expected);
8931 
8932         // Set the previous package name / calling uid to go back to the initial state.
8933         mContext.packageName = previousPackageName;
8934         mMockContext.binder.callingUid = previousUid;
8935     }
8936 
8937     private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
8938         assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
8939     }
8940 
8941     private void assertCheckProvisioningPreCondition(
8942             String action, String packageName, int provisioningCondition) {
8943         assertWithMessage("checkProvisioningPreCondition(%s, %s) returning unexpected result",
8944                 action, packageName).that(dpm.checkProvisioningPrecondition(action, packageName))
8945                         .isEqualTo(provisioningCondition);
8946     }
8947 
8948     /**
8949      * Setup a managed profile with the specified admin and its uid.
8950      * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
8951      * @param adminUid uid of the admin package.
8952      * @param copyFromAdmin package information for {@code admin} will be built based on this
8953      *     component's information.
8954      * @param appTargetSdk admin's target SDK level
8955      */
8956     private void addManagedProfile(
8957             ComponentName admin, int adminUid, ComponentName copyFromAdmin, int appTargetSdk)
8958             throws Exception {
8959         final int userId = UserHandle.getUserId(adminUid);
8960         getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
8961                 UserHandle.USER_SYSTEM);
8962         mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
8963         setUpPackageManagerForFakeAdmin(admin, adminUid, /* enabledSetting= */ null,
8964                 appTargetSdk, copyFromAdmin);
8965         dpm.setActiveAdmin(admin, false, userId);
8966         assertThat(dpm.setProfileOwner(admin, userId)).isTrue();
8967         mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
8968     }
8969 
8970     /**
8971      * Same as {@code addManagedProfile} above, except using development API level as the API
8972      * level of the admin.
8973      */
8974     private void addManagedProfile(
8975             ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
8976         addManagedProfile(admin, adminUid, copyFromAdmin, VERSION_CODES.CUR_DEVELOPMENT);
8977     }
8978 
8979     /**
8980      * Convert String[] to StringParceledListSlice.
8981      */
8982     private static StringParceledListSlice asSlice(String[] s) {
8983         return new StringParceledListSlice(Arrays.asList(s));
8984     }
8985 
8986     private void grantManageDeviceAdmins() {
8987         Log.d(TAG, "Granting " + permission.MANAGE_DEVICE_ADMINS);
8988         mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
8989     }
8990 
8991     private void mockPolicyExemptApps(String... apps) {
8992         Log.d(TAG, "Mocking R.array.policy_exempt_apps to return " + Arrays.toString(apps));
8993         when(mContext.resources.getStringArray(R.array.policy_exempt_apps)).thenReturn(apps);
8994     }
8995 
8996     private void mockVendorPolicyExemptApps(String... apps) {
8997         Log.d(TAG, "Mocking R.array.vendor_policy_exempt_apps to return " + Arrays.toString(apps));
8998         when(mContext.resources.getStringArray(R.array.vendor_policy_exempt_apps)).thenReturn(apps);
8999     }
9000 
9001     private void mockEmptyPolicyExemptApps() {
9002         when(mContext.getResources().getStringArray(R.array.policy_exempt_apps))
9003                 .thenReturn(new String[0]);
9004         when(mContext.getResources().getStringArray(R.array.vendor_policy_exempt_apps))
9005                 .thenReturn(new String[0]);
9006     }
9007 
9008     private boolean isDeprecatedPasswordApisSupported() {
9009         return !mIsAutomotive;
9010     }
9011 
9012     private void assumeDeprecatedPasswordApisSupported() {
9013         assumeTrue("device doesn't support deprecated password APIs",
9014                 isDeprecatedPasswordApisSupported());
9015     }
9016 
9017     private static PasswordMetrics metricsForPassword(String password) {
9018         return PasswordMetrics.computeForCredential(LockscreenCredential.createPassword(password));
9019     }
9020 
9021     private static PasswordMetrics metricsForPin(String pin) {
9022         return PasswordMetrics.computeForCredential(LockscreenCredential.createPin(pin));
9023     }
9024 }
9025