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