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