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 
17 package com.android.cts.devicepolicy;
18 
19 import static com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier.assertMetricsLogged;
20 
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertNull;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assume.assumeTrue;
25 
26 import android.platform.test.annotations.FlakyTest;
27 import android.platform.test.annotations.LargeTest;
28 import android.platform.test.annotations.RequiresDevice;
29 import android.stats.devicepolicy.EventId;
30 
31 import com.android.cts.devicepolicy.annotations.LockSettingsTest;
32 import com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier;
33 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
34 import com.android.tradefed.device.DeviceNotAvailableException;
35 import com.android.tradefed.log.LogUtil.CLog;
36 
37 import com.google.common.collect.ImmutableMap;
38 
39 import org.junit.Ignore;
40 import org.junit.Test;
41 
42 import java.io.File;
43 import java.io.FileNotFoundException;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Collections;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.stream.Collectors;
51 
52 /**
53  * Set of tests for use cases that apply to profile and device owner.
54  * This class is the base class of MixedProfileOwnerTest, MixedDeviceOwnerTest and
55  * MixedManagedProfileOwnerTest and is abstract to avoid running spurious tests.
56  *
57  * NOTE: Not all tests are executed in the subclasses. Sometimes, if a test is not applicable to
58  * a subclass, they override it with an empty method.
59  */
60 public abstract class DeviceAndProfileOwnerTest extends BaseDevicePolicyTest {
61 
62     public static final String DEVICE_ADMIN_PKG = "com.android.cts.deviceandprofileowner";
63     public static final String DEVICE_ADMIN_APK = "CtsDeviceAndProfileOwnerApp.apk";
64     protected static final String ADMIN_RECEIVER_TEST_CLASS
65             = ".BaseDeviceAdminTest$BasicAdminReceiver";
66     protected static final String DEVICE_ADMIN_COMPONENT_FLATTENED =
67             DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS;
68 
69     protected static final String STORAGE_ENCRYPTION_TEST_CLASS = ".StorageEncryptionTest";
70     protected static final String IS_SYSTEM_USER_PARAM = "isSystemUser";
71 
72     protected static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver";
73     protected static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk";
74 
75     private static final String INTENT_SENDER_PKG = "com.android.cts.intent.sender";
76     private static final String INTENT_SENDER_APK = "CtsIntentSenderApp.apk";
77 
78     private static final String PERMISSIONS_APP_PKG = "com.android.cts.permissionapp";
79     private static final String PERMISSIONS_APP_APK = "CtsPermissionApp.apk";
80 
81     private static final String SIMPLE_PRE_M_APP_PKG = "com.android.cts.launcherapps.simplepremapp";
82     private static final String SIMPLE_PRE_M_APP_APK = "CtsSimplePreMApp.apk";
83 
84     private static final String APP_RESTRICTIONS_TARGET_APP_PKG
85             = "com.android.cts.apprestrictions.targetapp";
86     private static final String APP_RESTRICTIONS_TARGET_APP_APK = "CtsAppRestrictionsTargetApp.apk";
87 
88     public static final String CERT_INSTALLER_PKG = "com.android.cts.certinstaller";
89     public static final String CERT_INSTALLER_APK = "CtsCertInstallerApp.apk";
90 
91     protected static final String DELEGATE_APP_PKG = "com.android.cts.delegate";
92     protected static final String DELEGATE_APP_APK = "CtsDelegateApp.apk";
93     private static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
94     private static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
95     private static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
96     private static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
97     private static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
98     private static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
99     private static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
100 
101     protected static final String TEST_APP_APK = "CtsSimpleApp.apk";
102     private static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp";
103     protected static final String TEST_APP_LOCATION = "/data/local/tmp/";
104 
105     protected static final String PACKAGE_INSTALLER_PKG = "com.android.cts.packageinstaller";
106     protected static final String PACKAGE_INSTALLER_APK = "CtsPackageInstallerApp.apk";
107 
108     private static final String ACCOUNT_MANAGEMENT_PKG
109             = "com.android.cts.devicepolicy.accountmanagement";
110     private static final String ACCOUNT_MANAGEMENT_APK = "CtsAccountManagementDevicePolicyApp.apk";
111 
112     private static final String VPN_APP_PKG = "com.android.cts.vpnfirewall";
113     private static final String VPN_APP_APK = "CtsVpnFirewallApp.apk";
114     private static final String VPN_APP_API23_APK = "CtsVpnFirewallAppApi23.apk";
115     private static final String VPN_APP_API24_APK = "CtsVpnFirewallAppApi24.apk";
116     private static final String VPN_APP_NOT_ALWAYS_ON_APK = "CtsVpnFirewallAppNotAlwaysOn.apk";
117 
118     private static final String COMMAND_BLOCK_ACCOUNT_TYPE = "block-accounttype";
119     private static final String COMMAND_UNBLOCK_ACCOUNT_TYPE = "unblock-accounttype";
120 
121     private static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
122     private static final String DISALLOW_REMOVE_USER = "no_remove_user";
123     private static final String ACCOUNT_TYPE
124             = "com.android.cts.devicepolicy.accountmanagement.account.type";
125 
126     private static final String CUSTOMIZATION_APP_PKG = "com.android.cts.customizationapp";
127     private static final String CUSTOMIZATION_APP_APK = "CtsCustomizationApp.apk";
128 
129     private static final String AUTOFILL_APP_PKG = "com.android.cts.devicepolicy.autofillapp";
130     private static final String AUTOFILL_APP_APK = "CtsDevicePolicyAutofillApp.apk";
131 
132     private static final String CONTENT_CAPTURE_APP_PKG = "com.android.cts.devicepolicy.contentcaptureapp";
133     private static final String CONTENT_CAPTURE_APP_APK = "CtsDevicePolicyContentCaptureApp.apk";
134 
135     private static final String CONTENT_CAPTURE_SERVICE_PKG = "com.android.cts.devicepolicy.contentcaptureservice";
136     private static final String CONTENT_CAPTURE_SERVICE_APK = "CtsDevicePolicyContentCaptureService.apk";
137     private static final String CONTENT_SUGGESTIONS_APP_APK =
138             "CtsDevicePolicyContentSuggestionsApp.apk";
139 
140     protected static final String ASSIST_APP_PKG = "com.android.cts.devicepolicy.assistapp";
141     protected static final String ASSIST_APP_APK = "CtsDevicePolicyAssistApp.apk";
142 
143     private static final String PRINTING_APP_PKG = "com.android.cts.devicepolicy.printingapp";
144     private static final String PRINTING_APP_APK = "CtsDevicePolicyPrintingApp.apk";
145 
146     private static final String METERED_DATA_APP_PKG
147             = "com.android.cts.devicepolicy.meteredtestapp";
148     private static final String METERED_DATA_APP_APK = "CtsMeteredDataTestApp.apk";
149 
150     // For testing key pair grants since they are per-uid
151     private static final String SHARED_UID_APP1_APK = "SharedUidApp1.apk";
152     private static final String SHARED_UID_APP2_APK = "SharedUidApp2.apk";
153 
154     private static final String ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES
155             = "enabled_notification_policy_access_packages";
156 
157     protected static final String ASSIST_INTERACTION_SERVICE =
158             ASSIST_APP_PKG + "/.MyInteractionService";
159 
160     private static final String ARG_ALLOW_FAILURE = "allowFailure";
161     private static final String ARG_LOGGING_TEST = "loggingTest";
162 
163     private static final String RESTRICT_BACKGROUND_GET_CMD =
164         "cmd netpolicy get restrict-background";
165     private static final String RESTRICT_BACKGROUND_ON_CMD =
166         "cmd netpolicy set restrict-background true";
167     private static final String RESTRICT_BACKGROUND_OFF_CMD =
168         "cmd netpolicy set restrict-background false";
169 
170     // The following constants were copied from DevicePolicyManager
171     private static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
172     private static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
173     private static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
174     private static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
175     private static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
176     private static final String DISALLOW_CONFIG_LOCATION = "no_config_location";
177     private static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
178     private static final String DISALLOW_AUTOFILL = "no_autofill";
179     private static final String SKIP_FIRST_USE_HINTS = "skip_first_use_hints";
180     private static final String DEFAULT_INPUT_METHOD = "default_input_method";
181     private static final int PERMISSION_POLICY_PROMPT = 0;
182     private static final int PERMISSION_POLICY_AUTO_GRANT = 1;
183     private static final int PERMISSION_POLICY_AUTO_DENY = 2;
184     private static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
185     private static final int PERMISSION_GRANT_STATE_GRANTED = 1;
186     private static final int PERMISSION_GRANT_STATE_DENIED = 2;
187     private static final String PARAM_APP_TO_ENABLE = "app_to_enable";
188     public static final String RESOLVE_ACTIVITY_CMD = "cmd package resolve-activity --brief %s | tail -n 1";
189 
190     private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent";
191 
192     // ID of the user all tests are run as. For device owner this will be the current user, for
193     // profile owner it is the user id of the created profile.
194     protected int mUserId;
195 
196     @Override
tearDown()197     public void tearDown() throws Exception {
198         getDevice().uninstallPackage(DEVICE_ADMIN_PKG);
199         getDevice().uninstallPackage(PERMISSIONS_APP_PKG);
200         getDevice().uninstallPackage(SIMPLE_PRE_M_APP_PKG);
201         getDevice().uninstallPackage(APP_RESTRICTIONS_TARGET_APP_PKG);
202         getDevice().uninstallPackage(CERT_INSTALLER_PKG);
203         getDevice().uninstallPackage(DELEGATE_APP_PKG);
204         getDevice().uninstallPackage(ACCOUNT_MANAGEMENT_PKG);
205         getDevice().uninstallPackage(VPN_APP_PKG);
206         getDevice().uninstallPackage(VPN_APP_API23_APK);
207         getDevice().uninstallPackage(VPN_APP_API24_APK);
208         getDevice().uninstallPackage(VPN_APP_NOT_ALWAYS_ON_APK);
209         getDevice().uninstallPackage(INTENT_RECEIVER_PKG);
210         getDevice().uninstallPackage(INTENT_SENDER_PKG);
211         getDevice().uninstallPackage(CUSTOMIZATION_APP_PKG);
212         getDevice().uninstallPackage(AUTOFILL_APP_PKG);
213         getDevice().uninstallPackage(CONTENT_CAPTURE_SERVICE_PKG);
214         getDevice().uninstallPackage(CONTENT_CAPTURE_APP_PKG);
215         getDevice().uninstallPackage(PRINTING_APP_PKG);
216         getDevice().uninstallPackage(METERED_DATA_APP_PKG);
217         getDevice().uninstallPackage(TEST_APP_PKG);
218 
219         // Press the HOME key to close any alart dialog that may be shown.
220         getDevice().executeShellCommand("input keyevent 3");
221 
222         super.tearDown();
223     }
224 
225     @Test
testCaCertManagement()226     public void testCaCertManagement() throws Exception {
227         executeDeviceTestClass(".CaCertManagementTest");
228     }
229 
230     @Test
testInstallCaCertLogged()231     public void testInstallCaCertLogged() throws Exception {
232         assertMetricsLogged(getDevice(), () -> {
233             executeDeviceTestMethod(".CaCertManagementTest", "testCanInstallAndUninstallACaCert");
234         }, new DevicePolicyEventWrapper.Builder(EventId.INSTALL_CA_CERT_VALUE)
235                     .setAdminPackageName(DEVICE_ADMIN_PKG)
236                     .setBoolean(false)
237                     .build(),
238             new DevicePolicyEventWrapper.Builder(EventId.UNINSTALL_CA_CERTS_VALUE)
239                     .setAdminPackageName(DEVICE_ADMIN_PKG)
240                     .setBoolean(false)
241                     .build());
242     }
243 
244     @Test
testApplicationRestrictionIsRestricted()245     public void testApplicationRestrictionIsRestricted() throws Exception {
246         installAppAsUser(DELEGATE_APP_APK, mUserId);
247         runDeviceTestsAsUser(DELEGATE_APP_PKG, ".AppRestrictionsIsCallerDelegateHelper",
248             "testAssertCallerIsNotApplicationRestrictionsManagingPackage", mUserId);
249         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".ApplicationRestrictionsIsCallerDelegateHelper",
250             "testSetApplicationRestrictionsManagingPackageToDelegate", mUserId);
251         runDeviceTestsAsUser(DELEGATE_APP_PKG, ".AppRestrictionsIsCallerDelegateHelper",
252             "testAssertCallerIsApplicationRestrictionsManagingPackage", mUserId);
253     }
254 
255     @Test
testApplicationRestrictions()256     public void testApplicationRestrictions() throws Exception {
257         installAppAsUser(DELEGATE_APP_APK, mUserId);
258         installAppAsUser(APP_RESTRICTIONS_TARGET_APP_APK, mUserId);
259 
260         try {
261             // Only the DPC can manage app restrictions by default.
262             executeDeviceTestClass(".ApplicationRestrictionsTest");
263             executeAppRestrictionsManagingPackageTest("testCannotAccessApis");
264 
265             // Letting the DELEGATE_APP_PKG manage app restrictions too.
266             changeApplicationRestrictionsManagingPackage(DELEGATE_APP_PKG);
267             executeAppRestrictionsManagingPackageTest("testCanAccessApis");
268             runDeviceTestsAsUser(DELEGATE_APP_PKG, ".GeneralDelegateTest",
269                     "testSettingAdminComponentNameThrowsException", mUserId);
270 
271             // The DPC should still be able to manage app restrictions normally.
272             executeDeviceTestClass(".ApplicationRestrictionsTest");
273 
274             // The app shouldn't be able to manage app restrictions for other users.
275             int parentUserId = getPrimaryUser();
276             if (parentUserId != mUserId) {
277                 installAppAsUser(DELEGATE_APP_APK, parentUserId);
278                 installAppAsUser(APP_RESTRICTIONS_TARGET_APP_APK, parentUserId);
279                 runDeviceTestsAsUser(DELEGATE_APP_PKG, ".AppRestrictionsDelegateTest",
280                         "testCannotAccessApis", parentUserId);
281             }
282 
283             // Revoking the permission for DELEGAYE_APP_PKG to manage restrictions.
284             changeApplicationRestrictionsManagingPackage(null);
285             executeAppRestrictionsManagingPackageTest("testCannotAccessApis");
286 
287             // The DPC should still be able to manage app restrictions normally.
288             executeDeviceTestClass(".ApplicationRestrictionsTest");
289 
290             assertMetricsLogged(getDevice(), () -> {
291                 executeDeviceTestMethod(".ApplicationRestrictionsTest",
292                         "testSetApplicationRestrictions");
293             }, new DevicePolicyEventWrapper.Builder(EventId.SET_APPLICATION_RESTRICTIONS_VALUE)
294                     .setAdminPackageName(DEVICE_ADMIN_PKG)
295                     .setStrings(APP_RESTRICTIONS_TARGET_APP_PKG)
296                     .build());
297         } finally {
298             changeApplicationRestrictionsManagingPackage(null);
299         }
300     }
301 
302     /**
303      * Returns a list of delegation tests that should run. Add delegations tests applicable to both
304      * device owner and profile owners to this method directly. DO or PO specific tests should be
305      * added to {@link #getAdditionalDelegationTests} in the subclass.
306      */
getDelegationTests()307     private Map<String, DevicePolicyEventWrapper[]> getDelegationTests() {
308         final Map<String, DevicePolicyEventWrapper[]> result = new HashMap<>();
309         result.put(".AppRestrictionsDelegateTest", null);
310         result.put(".CertInstallDelegateTest", null);
311         result.put(".BlockUninstallDelegateTest", null);
312         result.put(".PermissionGrantDelegateTest", null);
313         result.put(".PackageAccessDelegateTest", null);
314         result.put(".EnableSystemAppDelegateTest", null);
315         result.putAll(getAdditionalDelegationTests());
316         return result;
317     }
318 
getAdditionalDelegationTests()319     Map<String, DevicePolicyEventWrapper[]> getAdditionalDelegationTests() {
320         return Collections.<String, DevicePolicyEventWrapper[]>emptyMap();
321     }
322 
323     /**
324      * Returns a list of delegation scopes that are needed to run delegation tests. Add scopes
325      * which are applicable to both device owner and profile owners to this method directly.
326      * DO or PO specific scopes should be added to {@link #getAdditionalDelegationScopes}
327      * in the subclass.
328      */
getDelegationScopes()329     private List<String> getDelegationScopes() {
330         final List<String> result = new ArrayList<>(Arrays.asList(
331                 DELEGATION_APP_RESTRICTIONS,
332                 DELEGATION_CERT_INSTALL,
333                 DELEGATION_BLOCK_UNINSTALL,
334                 DELEGATION_PERMISSION_GRANT,
335                 DELEGATION_PACKAGE_ACCESS,
336                 DELEGATION_ENABLE_SYSTEM_APP,
337                 // CERT_SELECTION scope is in the list so it still participates GeneralDelegateTest.
338                 // But its main functionality test is driven by testDelegationCertSelection() and
339                 // hence missing from getDelegationTests() on purpose.
340                 DELEGATION_CERT_SELECTION
341                 ));
342         result.addAll(getAdditionalDelegationScopes());
343         return result;
344     }
345 
getAdditionalDelegationScopes()346     List<String> getAdditionalDelegationScopes() {
347         return Collections.<String>emptyList();
348     }
349 
350     /**
351      * General instructions to add a new delegation test:
352      * 1. Test primary delegation functionalitiy
353      *    Implement the delegate's positive/negate functionaility tests in a new test class
354      *    in CtsDelegateApp.apk. Main entry point are {@code testCanAccessApis} and
355      *    {@code testCannotAccessApis}. Once implemented, add the delegation scope and the test
356      *    class name to {@link #getDelegationScopes}, {@link #getDelegationTests} to make the test
357      *    run on DO/PO/PO on primary user.  If the test should only run on a subset of these
358      *    combinations, add them to the subclass's {@link #getAdditionalDelegationScopes} and
359      *    {@link #getDelegationScopes} intead.
360      *    <p>Alternatively, create a separate hostside method to drive the test, similar to
361      *    {@link #testDelegationCertSelection}. This is preferred if the delegated functionalities
362      *    already exist in another app.
363      * 2. Test access control of DO-only delegation
364      *    Add the delegation scope to
365      *    {@code DelegationTest#testDeviceOwnerOnlyDelegationsOnlyPossibleToBeSetByDeviceOwner} to
366      *    test that only DO can delegate this scope.
367      * 3. Test behaviour of exclusive delegation
368      *    Add the delegation scope to {@code DelegationTest#testExclusiveDelegations} to test that
369      *    the scope can only be delegatd to one app at a time.
370      */
371     @Test
testDelegation()372     public void testDelegation() throws Exception {
373         // Install relevant apps.
374         installDelegateApp();
375         installAppAsUser(TEST_APP_APK, mUserId);
376         installAppAsUser(APP_RESTRICTIONS_TARGET_APP_APK, mUserId);
377         if (isHeadlessSystemUserMode()) {
378             installAppAsUser(TEST_APP_APK, mDeviceOwnerUserId);
379             installAppAsUser(APP_RESTRICTIONS_TARGET_APP_APK, mDeviceOwnerUserId);
380         }
381 
382         try {
383             final Map<String, DevicePolicyEventWrapper[]> delegationTests = getDelegationTests();
384             // APIs are not accessible by default.
385             executeDelegationTests(delegationTests, false /* negative result */);
386 
387             // Granting the appropriate delegation scopes makes APIs accessible.
388             final List<String> scopes = getDelegationScopes();
389             setDelegatedScopes(DELEGATE_APP_PKG, scopes);
390             runDeviceTestsAsUser(DELEGATE_APP_PKG, ".GeneralDelegateTest", null, mUserId,
391                     ImmutableMap.of("scopes", String.join(",", scopes)));
392             executeDelegationTests(delegationTests, true /* positive result */);
393 
394             // APIs are not accessible after revoking delegations.
395             setDelegatedScopes(DELEGATE_APP_PKG, null);
396             executeDelegationTests(delegationTests, false /* negative result */);
397 
398             // Additional delegation tests.
399             executeDeviceTestClass(".DelegationTest");
400 
401         } finally {
402             // Remove any remaining delegations.
403             setDelegatedScopes(DELEGATE_APP_PKG, null);
404         }
405     }
406 
installDelegateApp()407     protected void installDelegateApp() throws Exception {
408         installAppAsUser(DELEGATE_APP_APK, mUserId);
409     }
410 
411     @Test
testDelegationCertSelection()412     public void testDelegationCertSelection() throws Exception {
413         installAppAsUser(CERT_INSTALLER_APK, mUserId);
414         setDelegatedScopes(CERT_INSTALLER_PKG, Arrays.asList(
415                 DELEGATION_CERT_INSTALL, DELEGATION_CERT_SELECTION));
416 
417         assertMetricsLogged(getDevice(), () -> {
418                 runDeviceTestsAsUser(CERT_INSTALLER_PKG, ".CertSelectionDelegateTest", mUserId);
419         }, new DevicePolicyEventWrapper.Builder(EventId.CHOOSE_PRIVATE_KEY_ALIAS_VALUE)
420                 .setAdminPackageName(CERT_INSTALLER_PKG)
421                 .setBoolean(true)
422                 .build());
423     }
424 
425     @Test
testPermissionGrant()426     public void testPermissionGrant() throws Exception {
427         installAppPermissionAppAsUser();
428         executeDeviceTestMethod(".PermissionsTest",
429                 "testPermissionGrantStateDenied_permissionRemainsDenied");
430         executeDeviceTestMethod(".PermissionsTest",
431                 "testPermissionGrantStateGranted_permissionRemainsGranted");
432     }
433 
434     @Test
testPermissionGrant_developmentPermission()435     public void testPermissionGrant_developmentPermission() throws Exception {
436         installAppPermissionAppAsUser();
437         executeDeviceTestMethod(
438                 ".PermissionsTest", "testPermissionGrantState_developmentPermission");
439     }
440 
441     @Test
testGrantOfSensorsRelatedPermissions()442     public void testGrantOfSensorsRelatedPermissions() throws Exception {
443         installAppPermissionAppAsUser();
444         executeDeviceTestMethod(".PermissionsTest", "testSensorsRelatedPermissionsCannotBeGranted");
445     }
446 
447     @Test
testDenyOfSensorsRelatedPermissions()448     public void testDenyOfSensorsRelatedPermissions() throws Exception {
449         installAppPermissionAppAsUser();
450         executeDeviceTestMethod(".PermissionsTest", "testSensorsRelatedPermissionsCanBeDenied");
451     }
452 
453     @Test
testSensorsRelatedPermissionsNotGrantedViaPolicy()454     public void testSensorsRelatedPermissionsNotGrantedViaPolicy() throws Exception {
455         installAppPermissionAppAsUser();
456         executeDeviceTestMethod(".PermissionsTest",
457                 "testSensorsRelatedPermissionsNotGrantedViaPolicy");
458     }
459 
460     @Test
testStateOfSensorsRelatedPermissionsCannotBeRead()461     public void testStateOfSensorsRelatedPermissionsCannotBeRead() throws Exception {
462         installAppPermissionAppAsUser();
463         executeDeviceTestMethod(".PermissionsTest",
464                 "testStateOfSensorsRelatedPermissionsCannotBeRead");
465     }
466 
467     /**
468      * Require a device for tests that use the network stack. Headless Androids running in
469      * data centres might need their network rules un-tampered-with in order to keep the ADB / VNC
470      * connection alive.
471      *
472      * This is only a problem on device owner / profile owner running on USER_SYSTEM, because
473      * network rules for this user will affect UID 0.
474      */
475     @RequiresDevice
476     @Test
testAlwaysOnVpn()477     public void testAlwaysOnVpn() throws Exception {
478         installAppAsUser(VPN_APP_APK, mUserId);
479         executeDeviceTestClassNoRestrictBackground(".AlwaysOnVpnTest");
480     }
481 
482     @RequiresDevice
483     @Test
testAlwaysOnVpnLockDown()484     public void testAlwaysOnVpnLockDown() throws Exception {
485         installAppAsUser(VPN_APP_APK, mUserId);
486         try {
487             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSet");
488             forceStopPackageForUser(VPN_APP_PKG, mUserId);
489             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testNetworkBlocked");
490         } finally {
491             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup");
492         }
493     }
494 
495     @RequiresDevice
496     @Test
testAlwaysOnVpnAcrossReboot()497     public void testAlwaysOnVpnAcrossReboot() throws Exception {
498         try {
499             installAppAsUser(VPN_APP_APK, mUserId);
500             waitForBroadcastIdle();
501             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSetWithAllowlist");
502             rebootAndWaitUntilReady();
503             // Make sure profile user initialization is complete before proceeding.
504             waitForBroadcastIdle();
505             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSetAfterReboot");
506         } finally {
507             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup");
508         }
509     }
510 
511     @RequiresDevice
512     @Test
testAlwaysOnVpnPackageUninstalled()513     public void testAlwaysOnVpnPackageUninstalled() throws Exception {
514         installAppAsUser(VPN_APP_APK, mUserId);
515         try {
516             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSet");
517             getDevice().uninstallPackage(VPN_APP_PKG);
518             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnVpnDisabled");
519             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testSetNonExistingPackage");
520         } finally {
521             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup");
522         }
523     }
524 
525     @RequiresDevice
526     @Test
testAlwaysOnVpnUnsupportedPackage()527     public void testAlwaysOnVpnUnsupportedPackage() throws Exception {
528         try {
529             // Target SDK = 23: unsupported
530             installAppAsUser(VPN_APP_API23_APK, mUserId);
531             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetUnsupportedVpnAlwaysOn");
532 
533             // Target SDK = 24: supported
534             installAppAsUser(VPN_APP_API24_APK, mUserId);
535             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn");
536             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn");
537 
538             // Explicit opt-out: unsupported
539             installAppAsUser(VPN_APP_NOT_ALWAYS_ON_APK, mUserId);
540             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetUnsupportedVpnAlwaysOn");
541         } finally {
542             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn");
543         }
544     }
545 
546     @RequiresDevice
547     @Test
testAlwaysOnVpnUnsupportedPackageReplaced()548     public void testAlwaysOnVpnUnsupportedPackageReplaced() throws Exception {
549         try {
550             // Target SDK = 24: supported
551             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testAssertNoAlwaysOnVpn");
552             installAppAsUser(VPN_APP_API24_APK, mUserId);
553             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn");
554             // Update the app to target higher API level, but with manifest opt-out
555             installAppAsUser(VPN_APP_NOT_ALWAYS_ON_APK, mUserId);
556             // wait for the app update install completed, ready to be tested
557             waitForBroadcastIdle();
558             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testAssertNoAlwaysOnVpn");
559         } finally {
560             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn");
561         }
562     }
563 
564     @RequiresDevice
565     @Test
testAlwaysOnVpnPackageLogged()566     public void testAlwaysOnVpnPackageLogged() throws Exception {
567         // Will be uninstalled in tearDown().
568         installAppAsUser(VPN_APP_APK, mUserId);
569         assertMetricsLogged(getDevice(), () -> {
570             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn");
571         }, new DevicePolicyEventWrapper.Builder(EventId.SET_ALWAYS_ON_VPN_PACKAGE_VALUE)
572                     .setAdminPackageName(DEVICE_ADMIN_PKG)
573                     .setStrings(VPN_APP_PKG)
574                     .setBoolean(true)
575                     .setInt(0)
576                     .build());
577     }
578 
579     @Test
testPermissionPolicy()580     public void testPermissionPolicy() throws Exception {
581         installAppPermissionAppAsUser();
582         executeDeviceTestMethod(".PermissionsTest",
583                 "testPermissionPolicyAutoDeny_permissionLocked");
584         executeDeviceTestMethod(".PermissionsTest",
585                 "testPermissionPolicyAutoGrant_permissionLocked");
586     }
587 
588     @Test
testAutoGrantMultiplePermissionsInGroup()589     public void testAutoGrantMultiplePermissionsInGroup() throws Exception {
590         installAppPermissionAppAsUser();
591         executeDeviceTestMethod(".PermissionsTest",
592                 "testPermissionPolicyAutoGrant_multiplePermissionsInGroup");
593     }
594 
595     @Test
testPermissionMixedPolicies()596     public void testPermissionMixedPolicies() throws Exception {
597         installAppPermissionAppAsUser();
598         executeDeviceTestMethod(".PermissionsTest",
599                 "testPermissionGrantStateDenied_mixedPolicies");
600         executeDeviceTestMethod(".PermissionsTest",
601                 "testPermissionGrantStateGranted_mixedPolicies");
602     }
603 
604     @Test
testPermissionGrantOfDisallowedPermissionWhileOtherPermIsGranted()605     public void testPermissionGrantOfDisallowedPermissionWhileOtherPermIsGranted()
606             throws Exception {
607         installAppPermissionAppAsUser();
608         executeDeviceTestMethod(".PermissionsTest",
609                 "testPermissionGrantStateDenied_otherPermissionIsGranted");
610     }
611 
612     @Test
613     @FlakyTest(bugId = 187862351)
testPermissionPrompts()614     public void testPermissionPrompts() throws Exception {
615         installAppPermissionAppAsUser();
616         executeDeviceTestMethod(".PermissionsTest", "testPermissionPrompts");
617     }
618 
619     @Test
testPermissionAppUpdate()620     public void testPermissionAppUpdate() throws Exception {
621         installAppPermissionAppAsUser();
622         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantStateDenied");
623         installAppPermissionAppAsUser();
624         executeDeviceTestMethod(".PermissionsTest", "testCannotRequestPermission");
625 
626         assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG));
627         installAppPermissionAppAsUser();
628         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantStateGranted");
629         installAppPermissionAppAsUser();
630         executeDeviceTestMethod(".PermissionsTest", "testCanRequestPermission");
631 
632         assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG));
633         installAppPermissionAppAsUser();
634         executeDeviceTestMethod(".PermissionsTest", "testPermissionPolicyAutoDeny");
635         installAppPermissionAppAsUser();
636         executeDeviceTestMethod(".PermissionsTest", "testCannotRequestPermission");
637 
638         assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG));
639         installAppPermissionAppAsUser();
640         executeDeviceTestMethod(".PermissionsTest", "testPermissionPolicyAutoGrant");
641         installAppPermissionAppAsUser();
642         executeDeviceTestMethod(".PermissionsTest", "testCanRequestPermission");
643     }
644 
645     @Test
testPermissionGrantPreMApp()646     public void testPermissionGrantPreMApp() throws Exception {
647         installAppAsUser(SIMPLE_PRE_M_APP_APK, mUserId);
648         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantState_preMApp");
649     }
650 
651     @Test
testPersistentIntentResolving()652     public void testPersistentIntentResolving() throws Exception {
653         executeDeviceTestClass(".PersistentIntentResolvingTest");
654         assertMetricsLogged(getDevice(), () -> {
655             executeDeviceTestMethod(".PersistentIntentResolvingTest",
656                     "testAddPersistentPreferredActivityYieldsReceptionAtTarget");
657         }, new DevicePolicyEventWrapper.Builder(EventId.ADD_PERSISTENT_PREFERRED_ACTIVITY_VALUE)
658                 .setAdminPackageName(DEVICE_ADMIN_PKG)
659                 .setStrings(DEVICE_ADMIN_PKG,
660                         "com.android.cts.deviceandprofileowner.EXAMPLE_ACTION")
661                 .build());
662     }
663 
664     @Test
testScreenCaptureDisabled()665     public void testScreenCaptureDisabled() throws Exception {
666         assertMetricsLogged(getDevice(), () -> {
667             // We need to ensure that the policy is deactivated for the device owner case, so making
668             // sure the second test is run even if the first one fails
669             try {
670                 setScreenCaptureDisabled(mUserId, true);
671             } finally {
672                 setScreenCaptureDisabled(mUserId, false);
673             }
674         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SCREEN_CAPTURE_DISABLED_VALUE)
675                     .setAdminPackageName(DEVICE_ADMIN_PKG)
676                     .setBoolean(true)
677                     .build(),
678             new DevicePolicyEventWrapper.Builder(EventId.SET_SCREEN_CAPTURE_DISABLED_VALUE)
679                     .setAdminPackageName(DEVICE_ADMIN_PKG)
680                     .setBoolean(false)
681                     .build());
682     }
683 
684     @Test
testScreenCaptureDisabled_assist()685     public void testScreenCaptureDisabled_assist() throws Exception {
686         try {
687             // Install and enable assistant, notice that profile can't have assistant.
688             installAppAsUser(ASSIST_APP_APK, mPrimaryUserId);
689             waitForBroadcastIdle();
690             setVoiceInteractionService(ASSIST_INTERACTION_SERVICE);
691             setScreenCaptureDisabled_assist(mUserId, true /* disabled */);
692         } finally {
693             setScreenCaptureDisabled_assist(mUserId, false /* disabled */);
694             clearVoiceInteractionService();
695         }
696     }
697 
698     @Test
testSupportMessage()699     public void testSupportMessage() throws Exception {
700         executeDeviceTestClass(".SupportMessageTest");
701         assertMetricsLogged(getDevice(), () -> {
702             executeDeviceTestMethod(".SupportMessageTest", "testShortSupportMessageSetGetAndClear");
703         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SHORT_SUPPORT_MESSAGE_VALUE)
704                 .setAdminPackageName(DEVICE_ADMIN_PKG)
705                 .build());
706         assertMetricsLogged(getDevice(), () -> {
707             executeDeviceTestMethod(".SupportMessageTest", "testLongSupportMessageSetGetAndClear");
708         }, new DevicePolicyEventWrapper.Builder(EventId.SET_LONG_SUPPORT_MESSAGE_VALUE)
709                 .setAdminPackageName(DEVICE_ADMIN_PKG)
710                 .build());
711     }
712 
713     @Test
testApplicationHidden()714     public void testApplicationHidden() throws Exception {
715         installAppPermissionAppAsUser();
716         executeDeviceTestClass(".ApplicationHiddenTest");
717         installAppAsUser(PERMISSIONS_APP_APK, mUserId);
718         assertMetricsLogged(getDevice(), () -> {
719             executeDeviceTestMethod(".ApplicationHiddenTest","testSetApplicationHidden");
720         }, new DevicePolicyEventWrapper.Builder(EventId.SET_APPLICATION_HIDDEN_VALUE)
721                 .setAdminPackageName(DEVICE_ADMIN_PKG)
722                 .setBoolean(false)
723                 .setStrings(PERMISSIONS_APP_PKG, "hidden", NOT_CALLED_FROM_PARENT)
724                 .build(),
725         new DevicePolicyEventWrapper.Builder(EventId.SET_APPLICATION_HIDDEN_VALUE)
726                 .setAdminPackageName(DEVICE_ADMIN_PKG)
727                 .setBoolean(false)
728                 .setStrings(PERMISSIONS_APP_PKG, "not_hidden", NOT_CALLED_FROM_PARENT)
729                 .build());
730     }
731 
732     @Test
testApplicationHidden_cannotHidePolicyExemptApps()733     public void testApplicationHidden_cannotHidePolicyExemptApps() throws Exception {
734         executeDeviceTestMethod(".ApplicationHiddenTest", "testCannotHidePolicyExemptApps");
735     }
736 
737     @Test
testAccountManagement_deviceAndProfileOwnerAlwaysAllowed()738     public void testAccountManagement_deviceAndProfileOwnerAlwaysAllowed() throws Exception {
739         installAppAsUser(ACCOUNT_MANAGEMENT_APK, mUserId);
740         executeDeviceTestClass(".AllowedAccountManagementTest");
741     }
742 
743     @Test
testAccountManagement_userRestrictionAddAccount()744     public void testAccountManagement_userRestrictionAddAccount() throws Exception {
745         installAppAsUser(ACCOUNT_MANAGEMENT_APK, mUserId);
746         try {
747             changeUserRestrictionOrFail(DISALLOW_MODIFY_ACCOUNTS, true, mUserId);
748             executeAccountTest("testAddAccount_blocked");
749         } finally {
750             // Ensure we clear the user restriction
751             changeUserRestrictionOrFail(DISALLOW_MODIFY_ACCOUNTS, false, mUserId);
752         }
753         executeAccountTest("testAddAccount_allowed");
754     }
755 
756     @Test
testAccountManagement_userRestrictionRemoveAccount()757     public void testAccountManagement_userRestrictionRemoveAccount() throws Exception {
758         installAppAsUser(ACCOUNT_MANAGEMENT_APK, mUserId);
759         try {
760             changeUserRestrictionOrFail(DISALLOW_MODIFY_ACCOUNTS, true, mUserId);
761             executeAccountTest("testRemoveAccount_blocked");
762         } finally {
763             // Ensure we clear the user restriction
764             changeUserRestrictionOrFail(DISALLOW_MODIFY_ACCOUNTS, false, mUserId);
765         }
766         executeAccountTest("testRemoveAccount_allowed");
767     }
768 
769     @Test
testAccountManagement_disabledAddAccount()770     public void testAccountManagement_disabledAddAccount() throws Exception {
771         installAppAsUser(ACCOUNT_MANAGEMENT_APK, mUserId);
772         try {
773             changeAccountManagement(COMMAND_BLOCK_ACCOUNT_TYPE, ACCOUNT_TYPE, mUserId);
774             executeAccountTest("testAddAccount_blocked");
775         } finally {
776             // Ensure we remove account management policies
777             changeAccountManagement(COMMAND_UNBLOCK_ACCOUNT_TYPE, ACCOUNT_TYPE, mUserId);
778         }
779         executeAccountTest("testAddAccount_allowed");
780     }
781 
782     @Test
testAccountManagement_disabledRemoveAccount()783     public void testAccountManagement_disabledRemoveAccount() throws Exception {
784         installAppAsUser(ACCOUNT_MANAGEMENT_APK, mUserId);
785         try {
786             changeAccountManagement(COMMAND_BLOCK_ACCOUNT_TYPE, ACCOUNT_TYPE, mUserId);
787             executeAccountTest("testRemoveAccount_blocked");
788         } finally {
789             // Ensure we remove account management policies
790             changeAccountManagement(COMMAND_UNBLOCK_ACCOUNT_TYPE, ACCOUNT_TYPE, mUserId);
791         }
792         executeAccountTest("testRemoveAccount_allowed");
793     }
794 
795     @Test
testDelegatedCertInstaller()796     public void testDelegatedCertInstaller() throws Exception {
797         installAppAsUser(CERT_INSTALLER_APK, mUserId);
798 
799         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerTest", mUserId);
800         assertMetricsLogged(getDevice(), () -> {
801             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerTest",
802                     "testInstallKeyPair", mUserId);
803         }, new DevicePolicyEventWrapper.Builder(EventId.SET_CERT_INSTALLER_PACKAGE_VALUE)
804                 .setAdminPackageName(DEVICE_ADMIN_PKG)
805                 .setStrings(CERT_INSTALLER_PKG)
806                 .build());
807     }
808 
809     public interface DelegatedCertInstallerTestAction {
run()810         void run() throws Exception;
811     }
812 
setUpDelegatedCertInstallerAndRunTests(DelegatedCertInstallerTestAction test)813     protected void setUpDelegatedCertInstallerAndRunTests(DelegatedCertInstallerTestAction test)
814             throws Exception {
815         installAppAsUser(CERT_INSTALLER_APK, mUserId);
816 
817         try {
818             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
819                     "testManualSetCertInstallerDelegate", mUserId);
820 
821             test.run();
822         } finally {
823             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
824                     "testManualClearCertInstallerDelegate", mUserId);
825         }
826     }
827 
828     // This test currently duplicates the testDelegatedCertInstaller, with one difference:
829     // The Delegated cert installer app is called directly rather than via intents from
830     // the DelegatedCertinstallerTest.
831     @Test
testDelegatedCertInstallerDirectly()832     public void testDelegatedCertInstallerDirectly() throws Exception {
833         setUpDelegatedCertInstallerAndRunTests(() ->
834             runDeviceTestsAsUser("com.android.cts.certinstaller",
835                     ".DirectDelegatedCertInstallerTest", mUserId));
836     }
837 
838     // This test generates a key pair and validates that an app can be silently granted
839     // access to it.
840     @Test
testSetKeyGrant()841     public void testSetKeyGrant() throws Exception {
842         // Install an app
843         installAppAsUser(CERT_INSTALLER_APK, mUserId);
844 
845         try {
846             // First, generate a key and grant the cert installer access to it.
847             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
848                     "testManualGenerateKeyAndGrantAccess", mUserId);
849             // Test the key is usable.
850             runDeviceTestsAsUser("com.android.cts.certinstaller",
851                     ".PreSelectedKeyAccessTest", "testAccessingPreSelectedAliasExpectingSuccess",
852                     mUserId);
853             // Remove the grant
854             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
855                     "testManualRemoveKeyGrant", mUserId);
856             // Run another test to make sure the app no longer has access to the key.
857             runDeviceTestsAsUser("com.android.cts.certinstaller",
858                     ".PreSelectedKeyAccessTest", "testAccessingPreSelectedAliasWithoutGrant", mUserId);
859         } finally {
860             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
861                     "testManualClearGeneratedKey", mUserId);
862         }
863     }
864 
865     // Sets restrictions and launches non-admin app, that tries to set wallpaper.
866     // Non-admin apps must not violate any user restriction.
867     @Test
testSetWallpaper_disallowed()868     public void testSetWallpaper_disallowed() throws Exception {
869         // UserManager.DISALLOW_SET_WALLPAPER
870         final String DISALLOW_SET_WALLPAPER = "no_set_wallpaper";
871         if (!hasService("wallpaper")) {
872             CLog.d("testSetWallpaper_disallowed(): device does not support wallpapers");
873             return;
874         }
875 
876         installAppAsUser(CUSTOMIZATION_APP_APK, mUserId);
877         try {
878             changeUserRestrictionOrFail(DISALLOW_SET_WALLPAPER, true, mUserId);
879             runDeviceTestsAsUser(CUSTOMIZATION_APP_PKG, ".CustomizationTest",
880                 "testSetWallpaper_disallowed", mUserId);
881         } finally {
882             changeUserRestrictionOrFail(DISALLOW_SET_WALLPAPER, false, mUserId);
883         }
884     }
885 
886     // Runs test with admin privileges. The test methods set all the tested restrictions
887     // inside. But these restrictions must have no effect on the device/profile owner behavior.
888     @Test
testDisallowSetWallpaper_allowed()889     public void testDisallowSetWallpaper_allowed() throws Exception {
890         if (!hasService("wallpaper")) {
891             CLog.d("testDisallowSetWallpaper_allowed(): device does not support wallpapers");
892             return;
893         }
894         executeDeviceTestMethod(".CustomizationRestrictionsTest",
895                 "testDisallowSetWallpaper_allowed");
896     }
897 
898     @Test
testDisallowAutofill_allowed()899     public void testDisallowAutofill_allowed() throws Exception {
900         boolean hasAutofill = hasDeviceFeature("android.software.autofill");
901         if (!hasAutofill) {
902           return;
903         }
904         installAppAsUser(AUTOFILL_APP_APK, mUserId);
905 
906         executeDeviceTestMethod(".AutofillRestrictionsTest",
907                 "testDisallowAutofill_allowed");
908     }
909 
910     @Test
testDisallowContentCapture_allowed()911     public void testDisallowContentCapture_allowed() throws Exception {
912         boolean hasContentCapture = hasService("content_capture");
913         if (!hasContentCapture) {
914             return;
915         }
916         installAppAsUser(CONTENT_CAPTURE_SERVICE_APK, mUserId);
917         installAppAsUser(CONTENT_CAPTURE_APP_APK, mUserId);
918 
919         setDefaultContentCaptureServiceEnabled(false);
920         try {
921             executeDeviceTestMethod(".ContentCaptureRestrictionsTest",
922                     "testDisallowContentCapture_allowed");
923         } finally {
924             setDefaultContentCaptureServiceEnabled(true);
925         }
926     }
927 
928     @Test
testDisallowContentSuggestions_allowed()929     public void testDisallowContentSuggestions_allowed() throws Exception {
930         boolean hasContentSuggestions = hasService("content_suggestions");
931         if (!hasContentSuggestions) {
932             return;
933         }
934         installAppAsUser(CONTENT_SUGGESTIONS_APP_APK, mUserId);
935 
936         setDefaultContentSuggestionsServiceEnabled(false);
937         try {
938             executeDeviceTestMethod(".ContentSuggestionsRestrictionsTest",
939                     "testDisallowContentSuggestions_allowed");
940         } finally {
941             setDefaultContentSuggestionsServiceEnabled(true);
942         }
943     }
944 
setDefaultContentSuggestionsServiceEnabled(boolean enabled)945     private void setDefaultContentSuggestionsServiceEnabled(boolean enabled)
946             throws DeviceNotAvailableException {
947         CLog.d("setDefaultContentSuggestionsServiceEnabled(" + mUserId + "): " + enabled);
948         getDevice().executeShellCommand(
949                 "cmd content_suggestions set default-service-enabled " + mUserId + " " + enabled);
950     }
951 
setDefaultContentCaptureServiceEnabled(boolean enabled)952     private void setDefaultContentCaptureServiceEnabled(boolean enabled)
953             throws Exception {
954         CLog.d("setDefaultServiceEnabled(" + mUserId + "): " + enabled);
955         getDevice().executeShellCommand(
956                 "cmd content_capture set default-service-enabled " + mUserId + " " + enabled);
957     }
958 
959     @Test
testSetMeteredDataDisabledPackages()960     public void testSetMeteredDataDisabledPackages() throws Exception {
961         assumeHasWifiFeature();
962 
963         installAppAsUser(METERED_DATA_APP_APK, mUserId);
964 
965         try (LocationModeSetter locationModeSetter = new LocationModeSetter(getDevice())) {
966             locationModeSetter.setLocationEnabled(true);
967             executeDeviceTestClass(".MeteredDataRestrictionTest");
968         }
969     }
970 
971     @Test
testPackageInstallUserRestrictions()972     public void testPackageInstallUserRestrictions() throws Exception {
973         boolean mIsWatch = hasDeviceFeature("android.hardware.type.watch");
974         if (mIsWatch) {
975             return;
976         }
977         // UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
978         final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
979         // UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
980         final String DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY =
981                 "no_install_unknown_sources_globally";
982         final String SECURE_SETTING_CATEGORY = "secure";
983         final String GLOBAL_SETTING_CATEGORY = "global";
984         final File apk = mBuildHelper.getTestFile(TEST_APP_APK);
985         try {
986             // Install the test and prepare the test apk.
987             installAppAsUser(PACKAGE_INSTALLER_APK, mUserId);
988             assertTrue(getDevice().pushFile(apk, TEST_APP_LOCATION + apk.getName()));
989             setInstallPackageAppOps(PACKAGE_INSTALLER_PKG, true, mUserId);
990 
991             // Add restrictions and test if we can install the apk.
992             getDevice().uninstallPackage(TEST_APP_PKG);
993             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES, true, mUserId);
994             runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest",
995                     "testManualInstallBlocked", mUserId);
996 
997             // Clear restrictions and test if we can install the apk.
998             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES, false, mUserId);
999 
1000             // Add global restriction and test if we can install the apk.
1001             getDevice().uninstallPackage(TEST_APP_PKG);
1002             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, true, mUserId);
1003             runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest",
1004                     "testManualInstallBlocked", mUserId);
1005 
1006             // Clear global restriction and test if we can install the apk.
1007             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, false, mUserId);
1008             runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest",
1009                     "testManualInstallSucceeded", mUserId);
1010         } finally {
1011             setInstallPackageAppOps(PACKAGE_INSTALLER_PKG, false, mUserId);
1012             String command = "rm " + TEST_APP_LOCATION + apk.getName();
1013             getDevice().executeShellCommand(command);
1014             getDevice().uninstallPackage(TEST_APP_PKG);
1015             getDevice().uninstallPackage(PACKAGE_INSTALLER_PKG);
1016         }
1017     }
1018 
1019     @Test
testAudioRestriction()1020     public void testAudioRestriction() throws Exception {
1021         // This package may need to toggle zen mode for this test, so allow it to do so.
1022         allowNotificationPolicyAccess(DEVICE_ADMIN_PKG, mUserId);
1023         try {
1024             executeDeviceTestClass(".AudioRestrictionTest");
1025         } finally {
1026             disallowNotificationPolicyAccess(DEVICE_ADMIN_PKG, mUserId);
1027         }
1028     }
1029 
1030     @Test
testDisallowAdjustVolumeMutedLogged()1031     public void testDisallowAdjustVolumeMutedLogged() throws Exception {
1032         assertMetricsLogged(getDevice(), () -> {
1033             executeDeviceTestMethod(".DevicePolicyLoggingTest",
1034                     "testDisallowAdjustVolumeMutedLogged");
1035         }, new DevicePolicyEventWrapper.Builder(EventId.SET_MASTER_VOLUME_MUTED_VALUE)
1036                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1037                     .setBoolean(true)
1038                     .build(),
1039             new DevicePolicyEventWrapper.Builder(EventId.SET_MASTER_VOLUME_MUTED_VALUE)
1040                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1041                     .setBoolean(false)
1042                     .build());
1043     }
1044 
1045     @FlakyTest(bugId = 141314026)
1046     @Test
testSuspendPackage()1047     public void testSuspendPackage() throws Exception {
1048         CLog.i("runTestSuspendPackage() on user %d", mUserId);
1049 
1050         installAppAsUser(INTENT_SENDER_APK, mUserId);
1051         installAppAsUser(INTENT_RECEIVER_APK, mUserId);
1052         assertMetricsLogged(getDevice(), () -> {
1053             // Suspend a testing package.
1054             executeDeviceTestMethod(".SuspendPackageTest", "testSetPackagesSuspended");
1055         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PACKAGES_SUSPENDED_VALUE)
1056                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1057                     .setStrings(INTENT_RECEIVER_PKG)
1058                     .setBoolean(false)
1059                     .build());
1060         // Verify that the package is suspended from the PREVIOUS test and that the dialog is shown
1061         executeSuspendPackageTestMethod("testPackageSuspended");
1062 
1063         // Undo the suspend.
1064         executeDeviceTestMethod(".SuspendPackageTest", "testSetPackagesNotSuspended");
1065         // Verify that the package is not suspended from the PREVIOUS test and that the app launches
1066         executeSuspendPackageTestMethod("testPackageNotSuspended");
1067 
1068         // Verify we cannot suspend not suspendable packages.
1069         executeDeviceTestMethod(".SuspendPackageTest", "testSuspendNotSuspendablePackages");
1070     }
1071 
1072     @FlakyTest(bugId = 141314026)
1073     @Test
testSuspendPackageWithPackageManager()1074     public void testSuspendPackageWithPackageManager() throws Exception {
1075         CLog.i("runTestSuspendPackageWithPackageManager() on user %d", mUserId);
1076 
1077         installAppAsUser(INTENT_SENDER_APK, mUserId);
1078         installAppAsUser(INTENT_RECEIVER_APK, mUserId);
1079         // Suspend a testing package with the PackageManager
1080         executeDeviceTestMethod(".SuspendPackageTest",
1081                 "testSetPackagesSuspendedWithPackageManager");
1082         // Verify that the package is suspended from the PREVIOUS test and that the dialog is shown
1083         executeSuspendPackageTestMethod("testPackageSuspendedWithPackageManager");
1084 
1085         // Undo the suspend.
1086         executeDeviceTestMethod(".SuspendPackageTest",
1087                 "testSetPackagesNotSuspendedWithPackageManager");
1088         // Verify that the package is not suspended from the PREVIOUS test and that the app launches
1089         executeSuspendPackageTestMethod("testPackageNotSuspended");
1090     }
1091 
1092     @Test
testTrustAgentInfo()1093     public void testTrustAgentInfo() throws Exception {
1094         assumeHasSecureLockScreenFeature();
1095 
1096         executeDeviceTestClass(".TrustAgentInfoTest");
1097     }
1098 
1099     @FlakyTest(bugId = 141161038)
1100     @Test
testCannotRemoveUserIfRestrictionSet()1101     public void testCannotRemoveUserIfRestrictionSet() throws Exception {
1102         assumeCanCreateAdditionalUsers(1);
1103         assumeTrue("Outside of the primary user, setting DISALLOW_REMOVE_USER would not work",
1104                 mUserId == getPrimaryUser());
1105 
1106         final int userId = createUser();
1107         try {
1108             changeUserRestrictionOrFail(DISALLOW_REMOVE_USER, true, mUserId);
1109             assertFalse(getDevice().removeUser(userId));
1110         } finally {
1111             changeUserRestrictionOrFail(DISALLOW_REMOVE_USER, false, mUserId);
1112             assertTrue(getDevice().removeUser(userId));
1113         }
1114     }
1115 
1116     @Test
testCannotEnableOrDisableDeviceOwnerOrProfileOwner()1117     public void testCannotEnableOrDisableDeviceOwnerOrProfileOwner() throws Exception {
1118         // Try to disable a component in device owner/ profile owner.
1119         String result = disableComponentOrPackage(
1120                 mUserId, DEVICE_ADMIN_PKG + "/.SetPolicyActivity");
1121         assertTrue("Should throw SecurityException",
1122                 result.contains("java.lang.SecurityException"));
1123         // Try to disable the device owner/ profile owner package.
1124         result = disableComponentOrPackage(mUserId, DEVICE_ADMIN_PKG);
1125         assertTrue("Should throw SecurityException",
1126                 result.contains("java.lang.SecurityException"));
1127         // Try to enable a component in device owner/ profile owner.
1128         result = enableComponentOrPackage(
1129                 mUserId, DEVICE_ADMIN_PKG + "/.SetPolicyActivity");
1130         assertTrue("Should throw SecurityException",
1131                 result.contains("java.lang.SecurityException"));
1132         // Try to enable the device owner/ profile owner package.
1133         result = enableComponentOrPackage(mUserId, DEVICE_ADMIN_PKG);
1134         assertTrue("Should throw SecurityException",
1135                 result.contains("java.lang.SecurityException"));
1136 
1137     }
1138 
1139     @Test
testRequiredStrongAuthTimeout()1140     public void testRequiredStrongAuthTimeout() throws Exception {
1141         assumeHasSecureLockScreenFeature();
1142 
1143         executeDeviceTestClass(".RequiredStrongAuthTimeoutTest");
1144     }
1145 
1146     @Test
testCreateAdminSupportIntent()1147     public void testCreateAdminSupportIntent() throws Exception {
1148         executeDeviceTestClass(".PolicyTransparencyTest");
1149     }
1150 
1151     @Test
testSetCameraDisabledLogged()1152     public void testSetCameraDisabledLogged() throws Exception {
1153         assertMetricsLogged(getDevice(), () -> {
1154             executeDeviceTestMethod(".PolicyTransparencyTest", "testCameraDisabled");
1155         }, new DevicePolicyEventWrapper.Builder(EventId.SET_CAMERA_DISABLED_VALUE)
1156                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1157                     .setBoolean(true)
1158                     .setStrings(NOT_CALLED_FROM_PARENT)
1159                     .build(),
1160             new DevicePolicyEventWrapper.Builder(EventId.SET_CAMERA_DISABLED_VALUE)
1161                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1162                     .setBoolean(false)
1163                     .setStrings(NOT_CALLED_FROM_PARENT)
1164                     .build());
1165     }
1166 
1167     /** Test for resetPassword for all devices. */
1168     @Test
testResetPasswordDeprecated()1169     public void testResetPasswordDeprecated() throws Exception {
1170         assumeHasSecureLockScreenFeature();
1171 
1172         executeDeviceTestMethod(".ResetPasswordTest", "testResetPasswordDeprecated");
1173     }
1174 
1175     @LockSettingsTest
1176     @Test
testResetPasswordWithToken()1177     public void testResetPasswordWithToken() throws Exception {
1178         assumeHasSecureLockScreenFeature();
1179 
1180         // If ResetPasswordWithTokenTest for managed profile is executed before device owner and
1181         // primary user profile owner tests, password reset token would have been disabled for
1182         // the primary user, so executing ResetPasswordWithTokenTest on user 0 would fail. We allow
1183         // this and do not fail the test in this case.
1184         // This is the default test for MixedDeviceOwnerTest and MixedProfileOwnerTest,
1185         // MixedManagedProfileOwnerTest overrides this method to execute the same test more strictly
1186         // without allowing failures.
1187         executeResetPasswordWithTokenTests(/* allowFailures */ true);
1188     }
1189 
1190     @Test
testPasswordSufficientInitially()1191     public void testPasswordSufficientInitially() throws Exception {
1192         executeDeviceTestClass(".PasswordSufficientInitiallyTest");
1193     }
1194 
1195     @Test
testPasswordRequirementsApi()1196     public void testPasswordRequirementsApi() throws Exception {
1197         executeDeviceTestMethod(".PasswordRequirementsTest",
1198                 "testSettingConstraintsWithLowQualityThrowsOnRPlus");
1199         executeDeviceTestMethod(".PasswordRequirementsTest",
1200                 "testSettingConstraintsWithNumericQualityOnlyLengthAllowedOnRPlus");
1201         executeDeviceTestMethod(".PasswordRequirementsTest",
1202                 "testSettingConstraintsWithComplexQualityAndResetWithLowerQuality");
1203     }
1204 
1205     @Test
testGetCurrentFailedPasswordAttempts()1206     public void testGetCurrentFailedPasswordAttempts() throws Exception {
1207         assumeHasSecureLockScreenFeature();
1208 
1209         final String wrongPassword = TEST_PASSWORD + "5";
1210 
1211         changeUserCredential(TEST_PASSWORD, null /*oldCredential*/, mUserId);
1212         try {
1213             // Test that before trying an incorrect password there are 0 failed attempts.
1214             executeDeviceTestMethod(".GetCurrentFailedPasswordAttemptsTest",
1215                     "testNoFailedPasswordAttempts");
1216             // Try an incorrect password.
1217             assertFalse(verifyUserCredentialIsCorrect(wrongPassword, mUserId));
1218             // Test that now there is one failed attempt.
1219             executeDeviceTestMethod(".GetCurrentFailedPasswordAttemptsTest",
1220                     "testOneFailedPasswordAttempt");
1221             // Try an incorrect password.
1222             assertFalse(verifyUserCredentialIsCorrect(wrongPassword, mUserId));
1223             // Test that now there are two failed attempts.
1224             executeDeviceTestMethod(".GetCurrentFailedPasswordAttemptsTest",
1225                     "testTwoFailedPasswordAttempts");
1226             // TODO: re-enable the test below when b/110945754 is fixed.
1227             // Try the correct password and check the failed attempts number has been reset to 0.
1228             // assertTrue(verifyUserCredentialIsCorrect(testPassword, mUserId));
1229             // executeDeviceTestMethod(".GetCurrentFailedPasswordAttemptsTest",
1230             //         "testNoFailedPasswordAttempts");
1231         } finally {
1232             changeUserCredential(null /*newCredential*/, TEST_PASSWORD, mUserId);
1233         }
1234     }
1235 
1236     @Test
testPasswordExpiration()1237     public void testPasswordExpiration() throws Exception {
1238         assumeHasSecureLockScreenFeature();
1239 
1240         executeDeviceTestClass(".PasswordExpirationTest");
1241     }
1242 
1243     @Test
testGetPasswordExpiration()1244     public void testGetPasswordExpiration() throws Exception {
1245         assumeHasSecureLockScreenFeature();
1246 
1247         executeDeviceTestMethod(".GetPasswordExpirationTest",
1248                 "testGetPasswordExpiration");
1249         try {
1250             executeDeviceTestMethod(".GetPasswordExpirationTest",
1251                     "testGetPasswordExpirationUpdatedAfterPasswordReset_beforeReset");
1252             // Wait for 20 seconds so we can make sure that the expiration date is refreshed later.
1253             Thread.sleep(20000);
1254             changeUserCredential(TEST_PASSWORD, null, mUserId);
1255             executeDeviceTestMethod(".GetPasswordExpirationTest",
1256                     "testGetPasswordExpirationUpdatedAfterPasswordReset_afterReset");
1257         } finally {
1258             changeUserCredential(null, TEST_PASSWORD, mUserId);
1259         }
1260     }
1261 
1262     @Test
testPasswordQualityWithoutSecureLockScreen()1263     public void testPasswordQualityWithoutSecureLockScreen() throws Exception {
1264         assumeDoesNotHaveSecureLockScreenFeature();
1265 
1266         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UnavailableSecureLockScreenTest", mUserId);
1267     }
1268 
1269     @Test
testSetSystemSetting()1270     public void testSetSystemSetting() throws Exception {
1271         executeDeviceTestClass(".SetSystemSettingTest");
1272     }
1273 
executeResetPasswordWithTokenTests(boolean allowFailures)1274     protected void executeResetPasswordWithTokenTests(boolean allowFailures)
1275             throws Exception {
1276         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".ResetPasswordWithTokenTest", null, mUserId,
1277                 Collections.singletonMap(ARG_ALLOW_FAILURE, String.valueOf(allowFailures)));
1278     }
1279 
1280     @Test
testClearApplicationData_testPkg()1281     public void testClearApplicationData_testPkg() throws Exception {
1282         installAppAsUser(INTENT_RECEIVER_APK, mUserId);
1283         runDeviceTestsAsUser(INTENT_RECEIVER_PKG, INTENT_RECEIVER_PKG + ".ClearApplicationDataTest",
1284                 "testWriteToSharedPreference", mUserId);
1285         executeDeviceTestMethod(".ClearApplicationDataTest", "testClearApplicationData_testPkg");
1286         runDeviceTestsAsUser(INTENT_RECEIVER_PKG, INTENT_RECEIVER_PKG + ".ClearApplicationDataTest",
1287                 "testSharedPreferenceCleared", mUserId);
1288     }
1289 
1290     @Test
testClearApplicationData_deviceProvisioning()1291     public void testClearApplicationData_deviceProvisioning() throws Exception {
1292         // Clearing data of device configuration app should fail
1293         executeDeviceTestMethod(".ClearApplicationDataTest",
1294                 "testClearApplicationData_deviceProvisioning");
1295     }
1296 
1297     @Test
testClearApplicationData_activeAdmin()1298     public void testClearApplicationData_activeAdmin() throws Exception {
1299         // Clearing data of active admin should fail
1300         executeDeviceTestMethod(".ClearApplicationDataTest",
1301                 "testClearApplicationData_activeAdmin");
1302     }
1303 
1304     @Test
testPrintingPolicy()1305     public void testPrintingPolicy() throws Exception {
1306         assumeHasPrintFeature();
1307 
1308         installAppAsUser(PRINTING_APP_APK, mUserId);
1309         executeDeviceTestClass(".PrintingPolicyTest");
1310     }
1311 
1312     @Test
testKeyManagement()1313     public void testKeyManagement() throws Exception {
1314         installAppAsUser(SHARED_UID_APP1_APK, mUserId);
1315         installAppAsUser(SHARED_UID_APP2_APK, mUserId);
1316 
1317         executeDeviceTestClass(".KeyManagementTest");
1318     }
1319 
1320     @Test
testInstallKeyPairLogged()1321     public void testInstallKeyPairLogged() throws Exception {
1322         assertMetricsLogged(getDevice(), () -> {
1323                 executeDeviceTestMethod(".KeyManagementTest", "testCanInstallCertChain");
1324                 }, new DevicePolicyEventWrapper.Builder(EventId.INSTALL_KEY_PAIR_VALUE)
1325                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1326                 .setBoolean(false)
1327                 .setStrings("notCredentialManagementApp")
1328                 .build(),
1329                 new DevicePolicyEventWrapper.Builder(EventId.REMOVE_KEY_PAIR_VALUE)
1330                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1331                 .setBoolean(false)
1332                 .setStrings("notCredentialManagementApp")
1333                 .build());
1334     }
1335 
1336     @Test
testGenerateKeyPairLogged()1337     public void testGenerateKeyPairLogged() throws Exception {
1338         assertMetricsLogged(getDevice(), () -> {
1339                 executeDeviceTestMethod(
1340                         ".KeyManagementTest", "testCanGenerateKeyPairWithKeyAttestation");
1341                 }, new DevicePolicyEventWrapper.Builder(EventId.GENERATE_KEY_PAIR_VALUE)
1342                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1343                 .setBoolean(false)
1344                 .setInt(0)
1345                 .setStrings("RSA", "notCredentialManagementApp")
1346                 .build(),
1347                 new DevicePolicyEventWrapper.Builder(EventId.GENERATE_KEY_PAIR_VALUE)
1348                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1349                 .setBoolean(false)
1350                 .setInt(0)
1351                 .setStrings("EC", "notCredentialManagementApp")
1352                 .build());
1353 
1354     }
1355 
1356     @Test
testSetKeyPairCertificateLogged()1357     public void testSetKeyPairCertificateLogged() throws Exception {
1358         assertMetricsLogged(getDevice(), () -> {
1359                 executeDeviceTestMethod(".KeyManagementTest", "testCanSetKeyPairCert");
1360                 }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEY_PAIR_CERTIFICATE_VALUE)
1361                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1362                 .setBoolean(false)
1363                 .setStrings("notCredentialManagementApp")
1364                 .build());
1365     }
1366 
1367     @Test
testPermittedAccessibilityServices()1368     public void testPermittedAccessibilityServices() throws Exception {
1369         executeDeviceTestClass(".AccessibilityServicesTest");
1370         assertMetricsLogged(getDevice(), () -> {
1371             executeDeviceTestMethod(".AccessibilityServicesTest",
1372                     "testPermittedAccessibilityServices");
1373         }, new DevicePolicyEventWrapper
1374                 .Builder(EventId.SET_PERMITTED_ACCESSIBILITY_SERVICES_VALUE)
1375                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1376                 .setStrings((String[]) null)
1377                 .build(),
1378         new DevicePolicyEventWrapper
1379                 .Builder(EventId.SET_PERMITTED_ACCESSIBILITY_SERVICES_VALUE)
1380                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1381                 .setStrings((String[]) null)
1382                 .build(),
1383         new DevicePolicyEventWrapper
1384                 .Builder(EventId.SET_PERMITTED_ACCESSIBILITY_SERVICES_VALUE)
1385                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1386                 .setStrings("com.google.pkg.one", "com.google.pkg.two")
1387                 .build());
1388     }
1389 
1390     @Test
testPermittedInputMethods()1391     public void testPermittedInputMethods() throws Exception {
1392         executeDeviceTestMethod(".InputMethodsTest", "testPermittedInputMethodsThrowsIfWrongAdmin");
1393         assertMetricsLogged(getDevice(), () -> {
1394             executeDeviceTestMethod(".InputMethodsTest", "testPermittedInputMethods");
1395         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
1396                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1397                 .setStrings(NOT_CALLED_FROM_PARENT, new String[0])
1398                 .build(),
1399         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
1400                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1401                 .setStrings(NOT_CALLED_FROM_PARENT, new String[0])
1402                 .build(),
1403         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
1404                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1405                 .setStrings(NOT_CALLED_FROM_PARENT, "com.google.pkg.one", "com.google.pkg.two")
1406                 .build());
1407     }
1408 
1409     @Test
testSetStorageEncryption()1410     public void testSetStorageEncryption() throws Exception {
1411         Map<String, String> params =
1412                 ImmutableMap.of(IS_SYSTEM_USER_PARAM, String.valueOf(mUserId == USER_SYSTEM));
1413         runDeviceTestsAsUser(
1414                 DEVICE_ADMIN_PKG, STORAGE_ENCRYPTION_TEST_CLASS, null, mUserId, params);
1415     }
1416 
1417     @Test
testPasswordMethodsLogged()1418     public void testPasswordMethodsLogged() throws Exception {
1419         assertMetricsLogged(getDevice(), () -> {
1420             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testPasswordMethodsLogged");
1421         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_QUALITY_VALUE)
1422                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1423                     .setInt(PASSWORD_QUALITY_COMPLEX)
1424                     .setStrings(NOT_CALLED_FROM_PARENT)
1425                     .build(),
1426             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_LENGTH_VALUE)
1427                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1428                     .setInt(13)
1429                     .build(),
1430             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_NUMERIC_VALUE)
1431                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1432                     .setInt(14)
1433                     .build(),
1434             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_NON_LETTER_VALUE)
1435                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1436                     .setInt(15)
1437                     .build(),
1438             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_LETTERS_VALUE)
1439                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1440                     .setInt(16)
1441                     .build(),
1442             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_LOWER_CASE_VALUE)
1443                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1444                     .setInt(17)
1445                     .build(),
1446             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_UPPER_CASE_VALUE)
1447                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1448                     .setInt(18)
1449                     .build(),
1450             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_SYMBOLS_VALUE)
1451                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1452                     .setInt(19)
1453                     .build(),
1454                 new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_COMPLEXITY_VALUE)
1455                         .setAdminPackageName(DEVICE_ADMIN_PKG)
1456                         .setInt(0x50000)
1457                         .setBoolean(false)
1458                         .build());
1459     }
1460 
1461     @Test
testLockNowLogged()1462     public void testLockNowLogged() throws Exception {
1463         assertMetricsLogged(getDevice(), () -> {
1464             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testLockNowLogged");
1465         }, new DevicePolicyEventWrapper.Builder(EventId.LOCK_NOW_VALUE)
1466                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1467                 .setInt(0)
1468                 .build());
1469     }
1470 
1471     @Test
testSetKeyguardDisabledFeaturesLogged()1472     public void testSetKeyguardDisabledFeaturesLogged() throws Exception {
1473         assertMetricsLogged(getDevice(), () -> {
1474             executeDeviceTestMethod(
1475                     ".DevicePolicyLoggingTest", "testSetKeyguardDisabledFeaturesLogged");
1476         }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
1477                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1478                     .setInt(KEYGUARD_DISABLE_FEATURES_NONE)
1479                     .setStrings(NOT_CALLED_FROM_PARENT)
1480                     .build(),
1481             new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
1482                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1483                     .setInt(KEYGUARD_DISABLE_FINGERPRINT)
1484                     .setStrings(NOT_CALLED_FROM_PARENT)
1485                     .build(),
1486             new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
1487                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1488                     .setInt(KEYGUARD_DISABLE_TRUST_AGENTS)
1489                     .setStrings(NOT_CALLED_FROM_PARENT)
1490                     .build(),
1491             new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
1492                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1493                     .setInt(KEYGUARD_DISABLE_FEATURES_NONE)
1494                     .setStrings(NOT_CALLED_FROM_PARENT)
1495                     .build());
1496     }
1497 
1498     @Test
testSetKeyguardDisabledSecureCameraLogged()1499     public void testSetKeyguardDisabledSecureCameraLogged() throws Exception {
1500         assertMetricsLogged(getDevice(), () -> {
1501             executeDeviceTestMethod(
1502                     ".DevicePolicyLoggingTest", "testSetKeyguardDisabledSecureCameraLogged");
1503         }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
1504                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1505                 .setInt(KEYGUARD_DISABLE_SECURE_CAMERA)
1506                 .setStrings(NOT_CALLED_FROM_PARENT)
1507                 .build());
1508     }
1509 
1510     @Test
testSetKeyguardDisabledFeatures()1511     public void testSetKeyguardDisabledFeatures() throws Exception {
1512         executeDeviceTestMethod(".KeyguardDisabledFeaturesTest",
1513                 "testSetKeyguardDisabledFeatures");
1514     }
1515 
1516     @Test
testSetUserRestrictionLogged()1517     public void testSetUserRestrictionLogged() throws Exception {
1518         assertMetricsLogged(getDevice(), () -> {
1519             executeDeviceTestMethod(
1520                     ".DevicePolicyLoggingTest", "testSetUserRestrictionLogged");
1521         }, new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
1522                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1523                     .setStrings(DISALLOW_CONFIG_LOCATION, NOT_CALLED_FROM_PARENT)
1524                     .build(),
1525             new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
1526                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1527                     .setStrings(DISALLOW_CONFIG_LOCATION, NOT_CALLED_FROM_PARENT)
1528                     .build(),
1529             new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
1530                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1531                     .setStrings(DISALLOW_ADJUST_VOLUME, NOT_CALLED_FROM_PARENT)
1532                     .build(),
1533             new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
1534                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1535                     .setStrings(DISALLOW_ADJUST_VOLUME, NOT_CALLED_FROM_PARENT)
1536                     .build(),
1537             new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
1538                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1539                     .setStrings(DISALLOW_AUTOFILL, NOT_CALLED_FROM_PARENT)
1540                     .build(),
1541             new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
1542                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1543                     .setStrings(DISALLOW_AUTOFILL, NOT_CALLED_FROM_PARENT)
1544                     .build()
1545         );
1546     }
1547 
1548     @Test
testSetSecureSettingLogged()1549     public void testSetSecureSettingLogged() throws Exception {
1550         assertMetricsLogged(getDevice(), () -> {
1551             executeDeviceTestMethod(
1552                     ".DevicePolicyLoggingTest", "testSetSecureSettingLogged");
1553         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
1554                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1555                 .setStrings(SKIP_FIRST_USE_HINTS, "1")
1556                 .build(),
1557             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
1558                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1559                     .setStrings(SKIP_FIRST_USE_HINTS, "0")
1560                     .build(),
1561             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
1562                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1563                     .setStrings(DEFAULT_INPUT_METHOD, "com.example.input")
1564                     .build()
1565                     ,
1566             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
1567                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1568                     .setStrings(DEFAULT_INPUT_METHOD)
1569                     .build());
1570     }
1571 
1572     @Test
testSetPermissionPolicyLogged()1573     public void testSetPermissionPolicyLogged() throws Exception {
1574         assertMetricsLogged(getDevice(), () -> {
1575             executeDeviceTestMethod(
1576                     ".DevicePolicyLoggingTest", "testSetPermissionPolicyLogged");
1577         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_POLICY_VALUE)
1578                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1579                 .setInt(PERMISSION_POLICY_AUTO_DENY)
1580                 .setBoolean(false)
1581                 .build(),
1582         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_POLICY_VALUE)
1583                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1584                 .setInt(PERMISSION_POLICY_AUTO_GRANT)
1585                 .setBoolean(false)
1586                 .build(),
1587         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_POLICY_VALUE)
1588                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1589                 .setInt(PERMISSION_POLICY_PROMPT)
1590                 .setBoolean(false)
1591                 .build());
1592     }
1593 
1594     @Test
testSetPermissionGrantStateLogged()1595     public void testSetPermissionGrantStateLogged() throws Exception {
1596         installAppPermissionAppAsUser();
1597         assertMetricsLogged(getDevice(), () -> {
1598             executeDeviceTestMethod(
1599                     ".DevicePolicyLoggingTest", "testSetPermissionGrantStateLogged");
1600         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_GRANT_STATE_VALUE)
1601                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1602                     .setInt(PERMISSION_GRANT_STATE_GRANTED)
1603                     .setBoolean(false)
1604                     .setStrings("android.permission.READ_CONTACTS")
1605                     .build(),
1606             new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_GRANT_STATE_VALUE)
1607                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1608                     .setInt(PERMISSION_GRANT_STATE_DENIED)
1609                     .setBoolean(false)
1610                     .setStrings("android.permission.READ_CONTACTS")
1611                     .build(),
1612             new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_GRANT_STATE_VALUE)
1613                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1614                     .setInt(PERMISSION_GRANT_STATE_DEFAULT)
1615                     .setBoolean(false)
1616                     .setStrings("android.permission.READ_CONTACTS")
1617                     .build());
1618     }
1619 
1620     @Test
testSetAutoTimeRequired()1621     public void testSetAutoTimeRequired() throws Exception {
1622         assertMetricsLogged(getDevice(), () -> {
1623             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testSetAutoTimeRequired");
1624         }, new DevicePolicyEventWrapper.Builder(EventId.SET_AUTO_TIME_REQUIRED_VALUE)
1625                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1626                     .setBoolean(true)
1627                     .build(),
1628             new DevicePolicyEventWrapper.Builder(EventId.SET_AUTO_TIME_REQUIRED_VALUE)
1629                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1630                     .setBoolean(false)
1631                     .build());
1632     }
1633 
1634     @Test
testSetAutoTimeEnabled()1635     public void testSetAutoTimeEnabled() throws Exception {
1636         assertMetricsLogged(getDevice(), () -> {
1637             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testSetAutoTimeEnabled");
1638         }, new DevicePolicyEventWrapper.Builder(EventId.SET_AUTO_TIME_VALUE)
1639                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1640                     .setBoolean(true)
1641                     .build(),
1642             new DevicePolicyEventWrapper.Builder(EventId.SET_AUTO_TIME_VALUE)
1643                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1644                     .setBoolean(false)
1645                     .build());
1646     }
1647 
1648     @Test
testSetAutoTimeZoneEnabled()1649     public void testSetAutoTimeZoneEnabled() throws Exception {
1650         assertMetricsLogged(getDevice(), () -> {
1651                     executeDeviceTestMethod(".TimeManagementTest", "testSetAutoTimeZoneEnabled");
1652                 }, new DevicePolicyEventWrapper.Builder(EventId.SET_AUTO_TIME_ZONE_VALUE)
1653                         .setAdminPackageName(DEVICE_ADMIN_PKG)
1654                         .setBoolean(true)
1655                         .build(),
1656                 new DevicePolicyEventWrapper.Builder(EventId.SET_AUTO_TIME_ZONE_VALUE)
1657                         .setAdminPackageName(DEVICE_ADMIN_PKG)
1658                         .setBoolean(false)
1659                         .build());
1660     }
1661 
1662     @Test
testEnableSystemAppLogged()1663     public void testEnableSystemAppLogged() throws Exception {
1664         final List<String> enabledSystemPackageNames = getEnabledSystemPackageNames();
1665         // We enable an enabled package to not worry about restoring the state.
1666         final String systemPackageToEnable = enabledSystemPackageNames.get(0);
1667         final Map<String, String> params =
1668                 ImmutableMap.of(PARAM_APP_TO_ENABLE, systemPackageToEnable);
1669         assertMetricsLogged(getDevice(), () -> {
1670             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DevicePolicyLoggingTest",
1671                     "testEnableSystemAppLogged", mUserId, params);
1672         }, new DevicePolicyEventWrapper.Builder(EventId.ENABLE_SYSTEM_APP_VALUE)
1673                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1674                 .setBoolean(false)
1675                 .setStrings(systemPackageToEnable)
1676                 .build());
1677     }
1678 
1679     @Test
testEnableSystemAppWithIntentLogged()1680     public void testEnableSystemAppWithIntentLogged() throws Exception {
1681         final String systemPackageToEnable = getLaunchableSystemPackage();
1682         if (systemPackageToEnable == null) {
1683             return;
1684         }
1685         final Map<String, String> params =
1686                 ImmutableMap.of(PARAM_APP_TO_ENABLE, systemPackageToEnable);
1687         assertMetricsLogged(getDevice(), () -> {
1688             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DevicePolicyLoggingTest",
1689                     "testEnableSystemAppWithIntentLogged", mUserId, params);
1690         }, new DevicePolicyEventWrapper.Builder(EventId.ENABLE_SYSTEM_APP_WITH_INTENT_VALUE)
1691                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1692                 .setBoolean(false)
1693                 .setStrings("android.intent.action.MAIN")
1694                 .build());
1695     }
1696 
1697     @Test
testSetUninstallBlockedLogged()1698     public void testSetUninstallBlockedLogged() throws Exception {
1699         installAppAsUser(PERMISSIONS_APP_APK, mUserId);
1700         assertMetricsLogged(getDevice(), () -> {
1701             executeDeviceTestMethod(".DevicePolicyLoggingTest",
1702                     "testSetUninstallBlockedLogged");
1703         }, new DevicePolicyEventWrapper.Builder(EventId.SET_UNINSTALL_BLOCKED_VALUE)
1704                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1705                 .setBoolean(false)
1706                 .setStrings(PERMISSIONS_APP_PKG)
1707                 .build());
1708     }
1709 
1710     @Test
testIsDeviceOrganizationOwnedWithManagedProfile()1711     public void testIsDeviceOrganizationOwnedWithManagedProfile() throws Exception {
1712         executeDeviceTestMethod(".DeviceOwnershipTest",
1713                 "testCallingIsOrganizationOwnedWithManagedProfileExpectingFalse");
1714     }
1715 
1716     @LockSettingsTest
1717     @Test
testSecondaryLockscreen()1718     public void testSecondaryLockscreen() throws Exception {
1719         executeDeviceTestClass(".SecondaryLockscreenTest");
1720     }
1721 
getLaunchableSystemPackage()1722     private String getLaunchableSystemPackage() throws DeviceNotAvailableException {
1723         final List<String> enabledSystemPackageNames = getEnabledSystemPackageNames();
1724         for (String enabledSystemPackage : enabledSystemPackageNames) {
1725             final String result = getDevice().executeShellCommand(
1726                     String.format(RESOLVE_ACTIVITY_CMD, enabledSystemPackage));
1727             if (!result.contains("No activity found")) {
1728                 return enabledSystemPackage;
1729             }
1730         }
1731         return null;
1732     }
1733 
getEnabledSystemPackageNames()1734     private List<String> getEnabledSystemPackageNames() throws DeviceNotAvailableException {
1735         final String commandResult =
1736                 getDevice().executeShellCommand("pm list packages -e -s --user " + mUserId);
1737         final int prefixLength = "package:".length();
1738         return new ArrayList<>(Arrays.asList(commandResult.split("\n")))
1739                 .stream()
1740                 .map(line -> line.substring(prefixLength))
1741                 .collect(Collectors.toList());
1742     }
1743 
1744     @Test
testEnrollmentSpecificIdCorrectCalculation()1745     public void testEnrollmentSpecificIdCorrectCalculation() throws Exception {
1746 
1747         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".EnrollmentSpecificIdTest",
1748                 "testCorrectCalculationOfEsid", mUserId);
1749     }
1750 
1751     @Test
testEnrollmentSpecificIdCorrectCalculationLogged()1752     public void testEnrollmentSpecificIdCorrectCalculationLogged() throws Exception {
1753         boolean isManagedProfile = (mPrimaryUserId != mUserId);
1754 
1755         assertMetricsLogged(getDevice(), () -> {
1756             executeDeviceTestMethod(".EnrollmentSpecificIdTest",
1757                     "testCorrectCalculationOfEsid");
1758         }, new DevicePolicyEventWrapper.Builder(EventId.SET_ORGANIZATION_ID_VALUE)
1759                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1760                 .setBoolean(isManagedProfile)
1761                 .build());
1762     }
1763 
1764     @Test
testEnrollmentSpecificIdEmptyAndMultipleSet()1765     public void testEnrollmentSpecificIdEmptyAndMultipleSet() throws DeviceNotAvailableException {
1766         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".EnrollmentSpecificIdTest",
1767                 "testThrowsForEmptyOrganizationId", mUserId);
1768         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".EnrollmentSpecificIdTest",
1769                 "testThrowsWhenTryingToReSetOrganizationId", mUserId);
1770     }
1771 
1772     @Test
testAdminControlOverSensorPermissionGrantsDefault()1773     public void testAdminControlOverSensorPermissionGrantsDefault() throws Exception {
1774         // By default, admin should not be able to grant sensors-related permissions.
1775         executeDeviceTestMethod(".SensorPermissionGrantTest",
1776                 "testAdminCannotGrantSensorsPermission");
1777     }
1778 
1779     @Test
testAddNetworkWithKeychainKey_granted()1780     public void testAddNetworkWithKeychainKey_granted() throws Exception {
1781         assumeHasWifiFeature();
1782 
1783         executeDeviceTestMethod(".WifiTest", "testAddNetworkWithKeychainKey_granted");
1784     }
1785 
1786     @Test
testAddNetworkSuggestionWithKeychainKey_granted()1787     public void testAddNetworkSuggestionWithKeychainKey_granted() throws Exception {
1788         assumeHasWifiFeature();
1789 
1790         executeDeviceTestMethod(".WifiTest", "testAddNetworkSuggestionWithKeychainKey_granted");
1791     }
1792 
1793     @Test
testAddNetworkSuggestionWithKeychainKey_notGranted()1794     public void testAddNetworkSuggestionWithKeychainKey_notGranted() throws Exception {
1795         assumeHasWifiFeature();
1796 
1797         executeDeviceTestMethod(".WifiTest", "testAddNetworkSuggestionWithKeychainKey_notGranted");
1798     }
1799 
1800     @Test
testAddNetworkWithKeychainKey_notGranted()1801     public void testAddNetworkWithKeychainKey_notGranted() throws Exception {
1802         assumeHasWifiFeature();
1803 
1804         executeDeviceTestMethod(".WifiTest", "testAddNetworkWithKeychainKey_notGranted");
1805     }
1806 
1807     // TODO(b/184175078): Migrate test to Bedstead when the infra is ready.
1808     @Test
testGetNearbyNotificationStreamingPolicy_getsNearbyStreamingDisabledAsDefault()1809     public void testGetNearbyNotificationStreamingPolicy_getsNearbyStreamingDisabledAsDefault()
1810             throws Exception {
1811         executeDeviceTestMethod(
1812                 ".NearbyNotificationStreamingPolicyTest",
1813                 "testGetNearbyNotificationStreamingPolicy_getsNearbyStreamingDisabledAsDefault");
1814     }
1815 
1816     // TODO(b/184175078): Migrate test to Bedstead when the infra is ready.
1817     @Test
testSetNearbyNotificationStreamingPolicy_changesPolicy()1818     public void testSetNearbyNotificationStreamingPolicy_changesPolicy() throws Exception {
1819         executeDeviceTestMethod(
1820                 ".NearbyNotificationStreamingPolicyTest",
1821                 "testSetNearbyNotificationStreamingPolicy_changesPolicy");
1822     }
1823 
1824     // TODO(b/184175078): Migrate test to Bedstead when the infra is ready.
1825     @Test
testGetNearbyAppStreamingPolicy_getsNearbyStreamingDisabledAsDefault()1826     public void testGetNearbyAppStreamingPolicy_getsNearbyStreamingDisabledAsDefault()
1827             throws Exception {
1828         executeDeviceTestMethod(
1829                 ".NearbyAppStreamingPolicyTest",
1830                 "testGetNearbyAppStreamingPolicy_getsNearbyStreamingDisabledAsDefault");
1831     }
1832 
1833     // TODO(b/184175078): Migrate test to Bedstead when the infra is ready.
1834     @Test
testSetNearbyAppStreamingPolicy_changesPolicy()1835     public void testSetNearbyAppStreamingPolicy_changesPolicy() throws Exception {
1836         executeDeviceTestMethod(
1837                 ".NearbyAppStreamingPolicyTest", "testSetNearbyAppStreamingPolicy_changesPolicy");
1838     }
1839 
1840     /**
1841      * Executes a test class on device. Prior to running, turn off background data usage
1842      * restrictions, and restore the original restrictions after the test.
1843      */
executeDeviceTestClassNoRestrictBackground(String className)1844     private void executeDeviceTestClassNoRestrictBackground(String className) throws Exception {
1845         boolean originalRestriction = ensureRestrictBackgroundPolicyOff();
1846         try {
1847             executeDeviceTestClass(className);
1848         } catch (Exception e) {
1849             throw e;
1850         } finally {
1851             // if the test throws exception, still restore the policy
1852             restoreRestrictBackgroundPolicyTo(originalRestriction);
1853         }
1854     }
1855 
executeDeviceTestClass(String className)1856     protected void executeDeviceTestClass(String className) throws Exception {
1857         executeDeviceTestMethod(className, /* testName= */ null);
1858     }
1859 
executeDeviceTestMethod(String className, String testName)1860     protected void executeDeviceTestMethod(String className, String testName) throws Exception {
1861         executeDeviceTestMethod(className, testName, /* params= */ new HashMap<>());
1862     }
1863 
executeDeviceTestMethod(String className, String testName, Map<String, String> params)1864     protected void executeDeviceTestMethod(String className, String testName,
1865             Map<String, String> params) throws Exception {
1866         executeDeviceTestMethod(className, testName, mUserId, params);
1867     }
1868 
executeDeviceTestMethod(String className, String testName, int userId, Map<String, String> params)1869     protected void executeDeviceTestMethod(String className, String testName, int userId,
1870             Map<String, String> params) throws Exception {
1871         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, testName, userId, params);
1872     }
1873 
installAppPermissionAppAsUser()1874     protected void installAppPermissionAppAsUser()
1875             throws FileNotFoundException, DeviceNotAvailableException {
1876         installAppAsUser(PERMISSIONS_APP_APK, false, mUserId);
1877     }
1878 
executeSuspendPackageTestMethod(String testName)1879     private void executeSuspendPackageTestMethod(String testName) throws Exception {
1880         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".SuspendPackageTest", testName, mUserId);
1881     }
1882 
executeAccountTest(String testName)1883     private void executeAccountTest(String testName) throws DeviceNotAvailableException {
1884         runDeviceTestsAsUser(ACCOUNT_MANAGEMENT_PKG, ".AccountManagementTest",
1885                 testName, mUserId);
1886         // Send a home intent to dismiss an error dialog.
1887         String command = "am start -a android.intent.action.MAIN"
1888                 + " -c android.intent.category.HOME";
1889         CLog.i("Output for command " + command + ": " + getDevice().executeShellCommand(command));
1890     }
1891 
executeAppRestrictionsManagingPackageTest(String testName)1892     private void executeAppRestrictionsManagingPackageTest(String testName) throws Exception {
1893         runDeviceTestsAsUser(DELEGATE_APP_PKG,
1894                 ".AppRestrictionsDelegateTest", testName, mUserId);
1895     }
1896 
executeDelegationTests(Map<String, DevicePolicyEventWrapper[]> delegationTests, boolean positive)1897     private void executeDelegationTests(Map<String, DevicePolicyEventWrapper[]> delegationTests,
1898             boolean positive)
1899             throws Exception {
1900         for (Map.Entry<String, DevicePolicyEventWrapper[]> entry : delegationTests.entrySet()) {
1901             final String delegationTestClass = entry.getKey();
1902             final DevicePolicyEventWrapper[] expectedMetrics = entry.getValue();
1903             final DevicePolicyEventLogVerifier.Action testRun = () -> {
1904                 runDeviceTestsAsUser(DELEGATE_APP_PKG, delegationTestClass,
1905                         positive ? "testCanAccessApis" : "testCannotAccessApis", mUserId);
1906             };
1907             if (expectedMetrics != null && positive) {
1908                 assertMetricsLogged(getDevice(), testRun, expectedMetrics);
1909             } else {
1910                 testRun.apply();
1911             }
1912         }
1913     }
1914 
changeUserRestrictionOrFail(String key, boolean value, int userId)1915     private void changeUserRestrictionOrFail(String key, boolean value, int userId)
1916             throws DeviceNotAvailableException {
1917         changeUserRestrictionOrFail(key, value, userId, DEVICE_ADMIN_PKG);
1918     }
1919 
changeAccountManagement(String command, String accountType, int userId)1920     private void changeAccountManagement(String command, String accountType, int userId)
1921             throws DeviceNotAvailableException {
1922         changePolicyOrFail(command, "--es extra-account-type " + accountType, userId);
1923     }
1924 
changeApplicationRestrictionsManagingPackage(String packageName)1925     private void changeApplicationRestrictionsManagingPackage(String packageName)
1926             throws DeviceNotAvailableException {
1927         String packageNameExtra = (packageName != null)
1928                 ? "--es extra-package-name " + packageName : "";
1929         changePolicyOrFail("set-app-restrictions-manager", packageNameExtra, mUserId);
1930     }
1931 
setDelegatedScopes(String packageName, List<String> scopes)1932     protected void setDelegatedScopes(String packageName, List<String> scopes)
1933             throws DeviceNotAvailableException {
1934         final String packageNameExtra = "--es extra-package-name " + packageName;
1935         String scopesExtra = "";
1936         if (scopes != null && scopes.size() > 0) {
1937             scopesExtra = "--esa extra-scopes-list " + scopes.get(0);
1938             for (int i = 1; i < scopes.size(); ++i) {
1939                 scopesExtra += "," + scopes.get(i);
1940             }
1941         }
1942         final String extras = packageNameExtra + " " + scopesExtra;
1943 
1944         changePolicyOrFail("set-delegated-scopes", extras, mUserId);
1945     }
1946 
setInstallPackageAppOps(String packageName, boolean allowed, int userId)1947     private void setInstallPackageAppOps(String packageName, boolean allowed, int userId)
1948             throws DeviceNotAvailableException {
1949         String command = "appops set --user " + userId + " " + packageName + " " +
1950                 "REQUEST_INSTALL_PACKAGES "
1951                 + (allowed ? "allow" : "default");
1952         CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
1953     }
1954 
changePolicyOrFail(String command, String extras, int userId)1955     private void changePolicyOrFail(String command, String extras, int userId)
1956             throws DeviceNotAvailableException {
1957         changePolicyOrFail(command, extras, userId, DEVICE_ADMIN_PKG);
1958     }
1959 
1960     /**
1961      * Start SimpleActivity synchronously in a particular user.
1962      */
startSimpleActivityAsUser(int userId)1963     protected void startSimpleActivityAsUser(int userId) throws Exception {
1964         installAppAsUser(TEST_APP_APK, /* grantPermissions */ true, /* dontKillApp */ true, userId);
1965         startActivityAsUser(userId, TEST_APP_PKG, TEST_APP_PKG + ".SimpleActivity");
1966     }
1967 
setScreenCaptureDisabled(int userId, boolean disabled)1968     protected void setScreenCaptureDisabled(int userId, boolean disabled) throws Exception {
1969         String testMethodName = disabled
1970                 ? "testSetScreenCaptureDisabled_true"
1971                 : "testSetScreenCaptureDisabled_false";
1972         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
1973 
1974         testMethodName = disabled
1975                 ? "testScreenCaptureImpossible"
1976                 : "testScreenCapturePossible";
1977 
1978         startSimpleActivityAsUser(userId);
1979         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
1980         forceStopPackageForUser(TEST_APP_PKG, userId);
1981     }
1982 
setScreenCaptureDisabled_assist(int userId, boolean disabled)1983     protected void setScreenCaptureDisabled_assist(int userId, boolean disabled) throws Exception {
1984         // Set the policy.
1985         String testMethodName = disabled
1986                 ? "testSetScreenCaptureDisabled_true"
1987                 : "testSetScreenCaptureDisabled_false";
1988         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
1989         testMethodName = disabled
1990                 ? "testScreenCaptureImpossible_assist"
1991                 : "testScreenCapturePossible_assist";
1992 
1993         // Check whether the VoiceInteractionService can retrieve the screenshot.
1994         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
1995 
1996         if (userId == mPrimaryUserId) {
1997             // If testing for user-0, also make sure the existing screen can't be captured.
1998             runDeviceTestsAsUser(
1999                     DEVICE_ADMIN_PKG,
2000                     ".AssistScreenCaptureDisabledTest",
2001                     testMethodName,
2002                     mPrimaryUserId);
2003         }
2004 
2005         // Make sure the foreground activity is from the target user.
2006         startSimpleActivityAsUser(userId);
2007 
2008         runDeviceTestsAsUser(
2009                 DEVICE_ADMIN_PKG,
2010                 ".AssistScreenCaptureDisabledTest",
2011                 testMethodName,
2012                 mPrimaryUserId);
2013     }
2014 
2015     /**
2016      * Allows packageName to manage notification policy configuration, which
2017      * includes toggling zen mode.
2018      */
allowNotificationPolicyAccess(String packageName, int userId)2019     private void allowNotificationPolicyAccess(String packageName, int userId)
2020             throws DeviceNotAvailableException {
2021         List<String> enabledPackages = getEnabledNotificationPolicyPackages(userId);
2022         if (!enabledPackages.contains(packageName)) {
2023             enabledPackages.add(packageName);
2024             setEnabledNotificationPolicyPackages(enabledPackages, userId);
2025         }
2026     }
2027 
2028     /**
2029      * Disallows packageName to manage notification policy configuration, which
2030      * includes toggling zen mode.
2031      */
disallowNotificationPolicyAccess(String packageName, int userId)2032     private void disallowNotificationPolicyAccess(String packageName, int userId)
2033             throws DeviceNotAvailableException {
2034         List<String> enabledPackages = getEnabledNotificationPolicyPackages(userId);
2035         if (enabledPackages.contains(packageName)) {
2036             enabledPackages.remove(packageName);
2037             setEnabledNotificationPolicyPackages(enabledPackages, userId);
2038         }
2039     }
2040 
setEnabledNotificationPolicyPackages(List<String> packages, int userId)2041     private void setEnabledNotificationPolicyPackages(List<String> packages, int userId)
2042             throws DeviceNotAvailableException {
2043         getDevice().setSetting(userId, "secure", ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2044                 String.join(":", packages));
2045     }
2046 
getEnabledNotificationPolicyPackages(int userId)2047     private List<String> getEnabledNotificationPolicyPackages(int userId)
2048             throws DeviceNotAvailableException {
2049         String settingValue = getDevice().getSetting(userId, "secure",
2050                 ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2051         if (settingValue == null) {
2052             return new ArrayList<String>();
2053         }
2054         return new ArrayList<String>(Arrays.asList(settingValue.split(":|\n")));
2055     }
2056 
setVoiceInteractionService(String componentName)2057     protected void setVoiceInteractionService(String componentName)
2058             throws DeviceNotAvailableException {
2059         getDevice().setSetting(
2060                 mPrimaryUserId, "secure", "voice_interaction_service", componentName);
2061         getDevice().setSetting(mPrimaryUserId, "secure", "assist_structure_enabled", "1");
2062         getDevice().setSetting(mPrimaryUserId, "secure", "assist_screenshot_enabled", "1");
2063     }
2064 
clearVoiceInteractionService()2065     protected void clearVoiceInteractionService() throws DeviceNotAvailableException {
2066         getDevice().executeShellCommand("settings delete secure voice_interaction_service");
2067     }
2068 
2069     /**
2070      * Ensure that restrict background policy is off.
2071      * Returns the original status of restrict background policy.
2072      */
ensureRestrictBackgroundPolicyOff()2073     private boolean ensureRestrictBackgroundPolicyOff() throws Exception {
2074         String restriction = getDevice().executeShellCommand(RESTRICT_BACKGROUND_GET_CMD);
2075         if (restriction.contains("enabled")) {
2076             getDevice().executeShellCommand(RESTRICT_BACKGROUND_OFF_CMD);
2077             return true;
2078         }
2079         return false;
2080     }
2081 
restoreRestrictBackgroundPolicyTo(boolean restricted)2082     private void restoreRestrictBackgroundPolicyTo(boolean restricted) throws Exception {
2083         getDevice().executeShellCommand(
2084                 restricted ? RESTRICT_BACKGROUND_ON_CMD : RESTRICT_BACKGROUND_OFF_CMD);
2085     }
2086 }
2087