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.assertNull;
22 import static org.junit.Assert.assertTrue;
23 import static org.junit.Assume.assumeFalse;
24 import static org.junit.Assume.assumeTrue;
25 
26 import android.permission.flags.Flags;
27 import android.platform.test.annotations.FlakyTest;
28 import android.platform.test.annotations.LargeTest;
29 import android.platform.test.annotations.RequiresDevice;
30 import android.platform.test.annotations.RequiresFlagsEnabled;
31 import android.platform.test.flag.junit.CheckFlagsRule;
32 import android.platform.test.flag.junit.host.HostFlagsValueProvider;
33 import android.stats.devicepolicy.EventId;
34 
35 import com.android.cts.devicepolicy.DeviceAdminFeaturesCheckerRule.TemporarilyIgnoreOnHeadlessSystemUserMode;
36 import com.android.cts.devicepolicy.annotations.LockSettingsTest;
37 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
38 import com.android.tradefed.device.DeviceNotAvailableException;
39 import com.android.tradefed.log.LogUtil.CLog;
40 import com.android.tradefed.util.RunUtil;
41 
42 import com.google.common.collect.ImmutableMap;
43 
44 import org.junit.Ignore;
45 import org.junit.Rule;
46 import org.junit.Test;
47 
48 import java.io.File;
49 import java.io.FileNotFoundException;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.HashMap;
53 import java.util.List;
54 import java.util.Map;
55 import java.util.stream.Collectors;
56 
57 /**
58  * Set of tests for use cases that apply to profile and device owner.
59  * This class is the base class of MixedProfileOwnerTest, MixedDeviceOwnerTest and
60  * MixedManagedProfileOwnerTest and is abstract to avoid running spurious tests.
61  *
62  * NOTE: Not all tests are executed in the subclasses. Sometimes, if a test is not applicable to
63  * a subclass, they override it with an empty method.
64  */
65 public abstract class DeviceAndProfileOwnerTest extends BaseDevicePolicyTest {
66 
67     public static final String DEVICE_ADMIN_PKG = "com.android.cts.deviceandprofileowner";
68     public static final String DEVICE_ADMIN_APK = "CtsDeviceAndProfileOwnerApp.apk";
69     protected static final String ADMIN_RECEIVER_TEST_CLASS
70             = ".BaseDeviceAdminTest$BasicAdminReceiver";
71     protected static final String DEVICE_ADMIN_COMPONENT_FLATTENED =
72             DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS;
73 
74     protected static final String IS_SYSTEM_USER_PARAM = "isSystemUser";
75 
76     protected static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver";
77     protected static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk";
78 
79     private static final String INTENT_SENDER_PKG = "com.android.cts.intent.sender";
80     private static final String INTENT_SENDER_APK = "CtsIntentSenderApp.apk";
81 
82     private static final String PERMISSIONS_APP_PKG = "com.android.cts.permissionapp";
83     private static final String PERMISSIONS_APP_APK = "CtsPermissionApp.apk";
84 
85     private static final String SIMPLE_PRE_M_APP_PKG = "com.android.cts.launcherapps.simplepremapp";
86     private static final String SIMPLE_PRE_M_APP_APK = "CtsSimplePreMApp.apk";
87 
88     public static final String CERT_INSTALLER_PKG = "com.android.cts.certinstaller";
89     public static final String CERT_INSTALLER_APK = "CtsCertInstallerApp.apk";
90 
91     protected static final String DELEGATE_APP_PKG = "com.android.cts.delegate";
92     protected static final String DELEGATE_APP_APK = "CtsDelegateApp.apk";
93     private static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
94     private static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
95 
96     protected static final String TEST_APP_APK = "CtsSimpleApp.apk";
97     private static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp";
98     protected static final String TEST_APP_LOCATION = "/data/local/tmp/";
99 
100     protected static final String PACKAGE_INSTALLER_PKG = "com.android.cts.packageinstaller";
101     protected static final String PACKAGE_INSTALLER_APK = "CtsPackageInstallerApp.apk";
102 
103     private static final String VPN_APP_PKG = "com.android.cts.vpnfirewall";
104     private static final String VPN_APP_APK = "CtsVpnFirewallApp.apk";
105     private static final String VPN_APP_API23_APK = "CtsVpnFirewallAppApi23.apk";
106     private static final String VPN_APP_API24_APK = "CtsVpnFirewallAppApi24.apk";
107     private static final String VPN_APP_NOT_ALWAYS_ON_APK = "CtsVpnFirewallAppNotAlwaysOn.apk";
108 
109     private static final String DISALLOW_REMOVE_USER = "no_remove_user";
110 
111     private static final String AUTOFILL_APP_PKG = "com.android.cts.devicepolicy.autofillapp";
112     private static final String AUTOFILL_APP_APK = "CtsDevicePolicyAutofillApp.apk";
113 
114     private static final String CONTENT_CAPTURE_APP_PKG = "com.android.cts.devicepolicy.contentcaptureapp";
115     private static final String CONTENT_CAPTURE_APP_APK = "CtsDevicePolicyContentCaptureApp.apk";
116 
117     private static final String CONTENT_CAPTURE_SERVICE_PKG = "com.android.cts.devicepolicy.contentcaptureservice";
118     private static final String CONTENT_CAPTURE_SERVICE_APK = "CtsDevicePolicyContentCaptureService.apk";
119 
120     protected static final String ASSIST_APP_PKG = "com.android.cts.devicepolicy.assistapp";
121     protected static final String ASSIST_APP_APK = "CtsDevicePolicyAssistApp.apk";
122 
123     private static final String METERED_DATA_APP_PKG
124             = "com.android.cts.devicepolicy.meteredtestapp";
125     private static final String METERED_DATA_APP_APK = "CtsMeteredDataTestApp.apk";
126 
127     // For testing key pair grants since they are per-uid
128     private static final String SHARED_UID_APP1_APK = "SharedUidApp1.apk";
129     private static final String SHARED_UID_APP2_APK = "SharedUidApp2.apk";
130 
131     private static final String ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES
132             = "enabled_notification_policy_access_packages";
133 
134     protected static final String ASSIST_INTERACTION_SERVICE =
135             ASSIST_APP_PKG + "/.MyInteractionService";
136 
137     private static final String RESTRICT_BACKGROUND_GET_CMD =
138         "cmd netpolicy get restrict-background";
139     private static final String RESTRICT_BACKGROUND_ON_CMD =
140         "cmd netpolicy set restrict-background true";
141     private static final String RESTRICT_BACKGROUND_OFF_CMD =
142         "cmd netpolicy set restrict-background false";
143 
144     // The following constants were copied from DevicePolicyManager
145     private static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
146     private static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
147     private static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
148     private static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
149     private static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
150     private static final String DISALLOW_CONFIG_LOCATION = "no_config_location";
151     private static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
152     private static final String DISALLOW_AUTOFILL = "no_autofill";
153     private static final String SKIP_FIRST_USE_HINTS = "skip_first_use_hints";
154     private static final String DEFAULT_INPUT_METHOD = "default_input_method";
155     private static final int PERMISSION_POLICY_PROMPT = 0;
156     private static final int PERMISSION_POLICY_AUTO_GRANT = 1;
157     private static final int PERMISSION_POLICY_AUTO_DENY = 2;
158     private static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
159     private static final int PERMISSION_GRANT_STATE_GRANTED = 1;
160     private static final int PERMISSION_GRANT_STATE_DENIED = 2;
161     private static final String PARAM_APP_TO_ENABLE = "app_to_enable";
162     public static final String RESOLVE_ACTIVITY_CMD = "cmd package resolve-activity --brief --user %d %s | tail -n 1";
163 
164     private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent";
165 
166     // ID of the user all tests are run as. For device owner this will be the current user, for
167     // profile owner it is the user id of the created profile.
168     protected int mUserId;
169 
170     @Rule
171     public final CheckFlagsRule mCheckFlagsRule =
172             HostFlagsValueProvider.createCheckFlagsRule(this::getDevice);
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(AUTOFILL_APP_PKG);
188         getDevice().uninstallPackage(CONTENT_CAPTURE_SERVICE_PKG);
189         getDevice().uninstallPackage(CONTENT_CAPTURE_APP_PKG);
190         getDevice().uninstallPackage(METERED_DATA_APP_PKG);
191         getDevice().uninstallPackage(TEST_APP_PKG);
192 
193         // Press the HOME key to close any alart dialog that may be shown.
194         getDevice().executeShellCommand("input keyevent 3");
195 
196         super.tearDown();
197     }
198 
199     @Test
testApplicationRestrictionIsRestricted()200     public void testApplicationRestrictionIsRestricted() throws Exception {
201         installAppAsUser(DELEGATE_APP_APK, mUserId);
202         runDeviceTestsAsUser(DELEGATE_APP_PKG, ".AppRestrictionsIsCallerDelegateHelper",
203             "testAssertCallerIsNotApplicationRestrictionsManagingPackage", mUserId);
204         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".ApplicationRestrictionsIsCallerDelegateHelper",
205             "testSetApplicationRestrictionsManagingPackageToDelegate", mUserId);
206         runDeviceTestsAsUser(DELEGATE_APP_PKG, ".AppRestrictionsIsCallerDelegateHelper",
207             "testAssertCallerIsApplicationRestrictionsManagingPackage", mUserId);
208     }
209 
installDelegateApp()210     protected void installDelegateApp() throws Exception {
211         installAppAsUser(DELEGATE_APP_APK, mUserId);
212     }
213 
214     @Test
testDelegationCertSelection()215     public void testDelegationCertSelection() throws Exception {
216         installAppAsUser(CERT_INSTALLER_APK, mUserId);
217         setDelegatedScopes(CERT_INSTALLER_PKG, Arrays.asList(
218                 DELEGATION_CERT_INSTALL, DELEGATION_CERT_SELECTION));
219 
220         assertMetricsLogged(getDevice(), () -> {
221                 runDeviceTestsAsUser(CERT_INSTALLER_PKG, ".CertSelectionDelegateTest", mUserId);
222         }, new DevicePolicyEventWrapper.Builder(EventId.CHOOSE_PRIVATE_KEY_ALIAS_VALUE)
223                 .setAdminPackageName(CERT_INSTALLER_PKG)
224                 .setBoolean(true)
225                 .build());
226     }
227 
228     /**
229      * Require a device for tests that use the network stack. Headless Androids running in
230      * data centres might need their network rules un-tampered-with in order to keep the ADB / VNC
231      * connection alive.
232      *
233      * This is only a problem on device owner / profile owner running on USER_SYSTEM, because
234      * network rules for this user will affect UID 0.
235      */
236     @RequiresDevice
237     @Test
testAlwaysOnVpn()238     public void testAlwaysOnVpn() throws Exception {
239         assumeIsNotWatch();
240         int userId = getUserIdForAlwaysOnVpnTests();
241         installAppAsUser(VPN_APP_APK, userId);
242         executeDeviceTestClassNoRestrictBackground(".AlwaysOnVpnTest", userId);
243     }
244 
getUserIdForAlwaysOnVpnTests()245     protected int getUserIdForAlwaysOnVpnTests() {
246         return mUserId;
247     }
248 
249     @RequiresDevice
250     @Test
testAlwaysOnVpnLockDown()251     public void testAlwaysOnVpnLockDown() throws Exception {
252         assumeIsNotWatch();
253         int userId = getUserIdForAlwaysOnVpnTests();
254         installAppAsUser(VPN_APP_APK, userId);
255         try {
256             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSet", userId);
257             forceStopPackageForUser(VPN_APP_PKG, userId);
258             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testNetworkBlocked", userId);
259         } finally {
260             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup", userId);
261         }
262     }
263 
264     @RequiresDevice
265     @Test
testAlwaysOnVpnAcrossReboot()266     public void testAlwaysOnVpnAcrossReboot() throws Exception {
267         assumeIsNotWatch();
268         int userId = getUserIdForAlwaysOnVpnTests();
269         try {
270             installAppAsUser(VPN_APP_APK, userId);
271             waitForBroadcastIdle();
272             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSetWithAllowlist",
273                     userId);
274             rebootAndWaitUntilReady();
275             // Make sure profile user initialization is complete before proceeding.
276             waitForBroadcastIdle();
277             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSetAfterReboot",
278                     userId);
279         } finally {
280             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup", userId);
281         }
282     }
283 
284     @RequiresDevice
285     @Test
testAlwaysOnVpnPackageUninstalled()286     public void testAlwaysOnVpnPackageUninstalled() throws Exception {
287         assumeIsNotWatch();
288         int userId = getUserIdForAlwaysOnVpnTests();
289         installAppAsUser(VPN_APP_APK, userId);
290         try {
291             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSet", userId);
292             getDevice().uninstallPackage(VPN_APP_PKG);
293             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnVpnDisabled",
294                     userId);
295             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testSetNonExistingPackage",
296                     userId);
297         } finally {
298             executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup", userId);
299         }
300     }
301 
302     @RequiresDevice
303     @Test
testAlwaysOnVpnUnsupportedPackage()304     public void testAlwaysOnVpnUnsupportedPackage() throws Exception {
305         assumeIsNotWatch();
306         int userId = getUserIdForAlwaysOnVpnTests();
307         try {
308             // Target SDK = 23: unsupported
309             installAppAsUser(VPN_APP_API23_APK, userId);
310             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetUnsupportedVpnAlwaysOn",
311                     userId);
312 
313             // Target SDK = 24: supported
314             installAppAsUser(VPN_APP_API24_APK, userId);
315             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn",
316                     userId);
317             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn", userId);
318 
319             // Explicit opt-out: unsupported
320             installAppAsUser(VPN_APP_NOT_ALWAYS_ON_APK, userId);
321             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetUnsupportedVpnAlwaysOn",
322                     userId);
323         } finally {
324             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn", userId);
325         }
326     }
327 
328     @RequiresDevice
329     @Test
testAlwaysOnVpnUnsupportedPackageReplaced()330     public void testAlwaysOnVpnUnsupportedPackageReplaced() throws Exception {
331         assumeIsNotWatch();
332         int userId = getUserIdForAlwaysOnVpnTests();
333         try {
334             // Target SDK = 24: supported
335             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testAssertNoAlwaysOnVpn",
336                     userId);
337             installAppAsUser(VPN_APP_API24_APK, userId);
338             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn",
339                     userId);
340             // Update the app to target higher API level, but with manifest opt-out
341             installAppAsUser(VPN_APP_NOT_ALWAYS_ON_APK, userId);
342             // wait for the app update install completed, ready to be tested
343             waitForBroadcastIdle();
344             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testAssertNoAlwaysOnVpn",
345                     userId);
346         } finally {
347             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn", userId);
348         }
349     }
350 
351     @RequiresDevice
352     @Test
testAlwaysOnVpnPackageLogged()353     public void testAlwaysOnVpnPackageLogged() throws Exception {
354         assumeIsNotWatch();
355         int userId = getUserIdForAlwaysOnVpnTests();
356         // Will be uninstalled in tearDown().
357         installAppAsUser(VPN_APP_APK, userId);
358         assertMetricsLogged(getDevice(), () -> {
359             executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn",
360                     userId);
361         }, new DevicePolicyEventWrapper.Builder(EventId.SET_ALWAYS_ON_VPN_PACKAGE_VALUE)
362                     .setAdminPackageName(DEVICE_ADMIN_PKG)
363                     .setStrings(VPN_APP_PKG)
364                     .setBoolean(true)
365                     .setInt(0)
366                     .build());
367     }
368 
369     @Test
testPermissionPolicy()370     public void testPermissionPolicy() throws Exception {
371         installAppPermissionAppAsUser();
372         executeDeviceTestMethod(".PermissionsTest",
373                 "testPermissionPolicyAutoDeny_permissionLocked");
374         executeDeviceTestMethod(".PermissionsTest",
375                 "testPermissionPolicyAutoGrant_permissionLocked");
376     }
377 
378     @Test
testPermissionGrantOfDisallowedPermissionWhileOtherPermIsGranted()379     public void testPermissionGrantOfDisallowedPermissionWhileOtherPermIsGranted()
380             throws Exception {
381         installAppPermissionAppAsUser();
382         executeDeviceTestMethod(".PermissionsTest",
383                 "testPermissionGrantStateDenied_otherPermissionIsGranted");
384     }
385 
386     @Test
387     @FlakyTest(bugId = 205194911)
testPermissionPrompts()388     public void testPermissionPrompts() throws Exception {
389         installAppPermissionAppAsUser();
390         executeDeviceTestMethod(".PermissionsTest", "testPermissionPrompts");
391     }
392 
393     @Test
testPermissionAppUpdate()394     public void testPermissionAppUpdate() throws Exception {
395         //TODO(b/346501480): Investigate why this test is failing on Auto with a ProfileOwner.
396         assumeFalse(isAutomotive());
397 
398         installAppPermissionAppAsUser();
399         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantStateDenied");
400         installAppPermissionAppAsUser();
401         executeDeviceTestMethod(".PermissionsTest", "testCannotRequestPermission");
402 
403         assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG));
404         installAppPermissionAppAsUser();
405         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantStateGranted");
406         installAppPermissionAppAsUser();
407         executeDeviceTestMethod(".PermissionsTest", "testCanRequestPermission");
408 
409         assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG));
410         installAppPermissionAppAsUser();
411         executeDeviceTestMethod(".PermissionsTest", "testPermissionPolicyAutoDeny");
412         installAppPermissionAppAsUser();
413         executeDeviceTestMethod(".PermissionsTest", "testCannotRequestPermission");
414 
415         assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG));
416         installAppPermissionAppAsUser();
417         executeDeviceTestMethod(".PermissionsTest", "testPermissionPolicyAutoGrant");
418         installAppPermissionAppAsUser();
419         executeDeviceTestMethod(".PermissionsTest", "testCanRequestPermission");
420     }
421 
422     @Test
testPermissionGrantPreMApp()423     public void testPermissionGrantPreMApp() throws Exception {
424         installAppAsUser(SIMPLE_PRE_M_APP_APK, mUserId);
425 
426         if (isHeadlessSystemUserMode()) {
427             installAppAsUser(SIMPLE_PRE_M_APP_APK, mDeviceOwnerUserId);
428         }
429         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantState_preMApp");
430     }
431 
432     @Test
testScreenCaptureDisabled_assist()433     public void testScreenCaptureDisabled_assist() throws Exception {
434         //TODO(b/346501480): Investigate why this test is failing on Auto with a ProfileOwner.
435         assumeFalse(isAutomotive());
436         try {
437             // Install and enable assistant, notice that profile can't have assistant.
438             installAppAsUser(ASSIST_APP_APK, mPrimaryUserId);
439             waitForBroadcastIdle();
440             setVoiceInteractionService(ASSIST_INTERACTION_SERVICE);
441             setScreenCaptureDisabled_assist(mUserId, true /* disabled */);
442         } finally {
443             setScreenCaptureDisabled_assist(mUserId, false /* disabled */);
444             clearVoiceInteractionService();
445         }
446     }
447 
448     @TemporarilyIgnoreOnHeadlessSystemUserMode(bugId = "197859595",
449             reason = "Will be migrated to new test infra")
450     @Test
testDelegatedCertInstaller()451     public void testDelegatedCertInstaller() throws Exception {
452         installAppAsUser(CERT_INSTALLER_APK, mUserId);
453 
454         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerTest", mUserId);
455         assertMetricsLogged(getDevice(), () -> {
456             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerTest",
457                     "testInstallKeyPair", mUserId);
458         }, new DevicePolicyEventWrapper.Builder(EventId.SET_CERT_INSTALLER_PACKAGE_VALUE)
459                 .setAdminPackageName(DEVICE_ADMIN_PKG)
460                 .setStrings(CERT_INSTALLER_PKG)
461                 .build());
462     }
463 
464     public interface DelegatedCertInstallerTestAction {
run()465         void run() throws Exception;
466     }
467 
setUpDelegatedCertInstallerAndRunTests(DelegatedCertInstallerTestAction test)468     protected void setUpDelegatedCertInstallerAndRunTests(DelegatedCertInstallerTestAction test)
469             throws Exception {
470         installAppAsUser(CERT_INSTALLER_APK, mUserId);
471 
472         try {
473             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
474                     "testManualSetCertInstallerDelegate", mUserId);
475 
476             test.run();
477         } finally {
478             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
479                     "testManualClearCertInstallerDelegate", mUserId);
480         }
481     }
482 
483     // This test currently duplicates the testDelegatedCertInstaller, with one difference:
484     // The Delegated cert installer app is called directly rather than via intents from
485     // the DelegatedCertinstallerTest.
486     @TemporarilyIgnoreOnHeadlessSystemUserMode(bugId = "197859595",
487             reason = "Will be migrated to new test infra")
488     @Test
testDelegatedCertInstallerDirectly()489     public void testDelegatedCertInstallerDirectly() throws Exception {
490         assumeTrue(mHasAttestation);
491 
492         setUpDelegatedCertInstallerAndRunTests(() ->
493             runDeviceTestsAsUser("com.android.cts.certinstaller",
494                     ".DirectDelegatedCertInstallerTest", mUserId));
495     }
496 
497     // This test generates a key pair and validates that an app can be silently granted
498     // access to it.
499     @TemporarilyIgnoreOnHeadlessSystemUserMode(bugId = "197859595",
500             reason = "Will be migrated to new test infra")
501     @Test
testSetKeyGrant()502     public void testSetKeyGrant() throws Exception {
503         assumeTrue(mHasAttestation);
504 
505         // Install an app
506         installAppAsUser(CERT_INSTALLER_APK, mUserId);
507 
508         try {
509             // First, generate a key and grant the cert installer access to it.
510             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
511                     "testManualGenerateKeyAndGrantAccess", mUserId);
512             // Test the key is usable.
513             runDeviceTestsAsUser("com.android.cts.certinstaller",
514                     ".PreSelectedKeyAccessTest", "testAccessingPreSelectedAliasExpectingSuccess",
515                     mUserId);
516             // Remove the grant
517             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
518                     "testManualRemoveKeyGrant", mUserId);
519             // Run another test to make sure the app no longer has access to the key.
520             runDeviceTestsAsUser("com.android.cts.certinstaller",
521                     ".PreSelectedKeyAccessTest", "testAccessingPreSelectedAliasWithoutGrant", mUserId);
522         } finally {
523             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
524                     "testManualClearGeneratedKey", mUserId);
525         }
526     }
527 
528     // Runs test with admin privileges. The test methods set all the tested restrictions
529     // inside. But these restrictions must have no effect on the device/profile owner behavior.
530     @Test
testDisallowSetWallpaper_allowed()531     public void testDisallowSetWallpaper_allowed() throws Exception {
532         if (!hasService("wallpaper")) {
533             CLog.d("testDisallowSetWallpaper_allowed(): device does not support wallpapers");
534             return;
535         }
536         executeDeviceTestMethod(".CustomizationRestrictionsTest",
537                 "testDisallowSetWallpaper_allowed");
538     }
539 
540     @Test
testDisallowAutofill_allowed()541     public void testDisallowAutofill_allowed() throws Exception {
542         boolean hasAutofill = hasDeviceFeature("android.software.autofill");
543         if (!hasAutofill) {
544           return;
545         }
546         installAppAsUser(AUTOFILL_APP_APK, mUserId);
547 
548         executeDeviceTestMethod(".AutofillRestrictionsTest",
549                 "testDisallowAutofill_allowed");
550     }
551 
552     @Test
testDisallowContentCapture_allowed()553     public void testDisallowContentCapture_allowed() throws Exception {
554         boolean hasContentCapture = hasService("content_capture");
555         if (!hasContentCapture) {
556             return;
557         }
558         installAppAsUser(CONTENT_CAPTURE_SERVICE_APK, mUserId);
559         installAppAsUser(CONTENT_CAPTURE_APP_APK, mUserId);
560 
561         setDefaultContentCaptureServiceEnabled(false);
562         try {
563             executeDeviceTestMethod(".ContentCaptureRestrictionsTest",
564                     "testDisallowContentCapture_allowed");
565         } finally {
566             setDefaultContentCaptureServiceEnabled(true);
567         }
568     }
569 
setDefaultContentCaptureServiceEnabled(boolean enabled)570     private void setDefaultContentCaptureServiceEnabled(boolean enabled)
571             throws Exception {
572         CLog.d("setDefaultServiceEnabled(" + mUserId + "): " + enabled);
573         getDevice().executeShellCommand(
574                 "cmd content_capture set default-service-enabled " + mUserId + " " + enabled);
575     }
576 
577     @Test
testSetMeteredDataDisabledPackages()578     public void testSetMeteredDataDisabledPackages() throws Exception {
579         assumeHasWifiFeature();
580         assumeIsNotWatch();
581 
582         installAppAsUser(METERED_DATA_APP_APK, mUserId);
583 
584         try (LocationModeSetter locationModeSetter = new LocationModeSetter(getDevice())) {
585             locationModeSetter.setLocationEnabled(true);
586             executeDeviceTestClass(".MeteredDataRestrictionTest");
587         }
588     }
589 
590     @Test
testPackageInstallUserRestrictions()591     public void testPackageInstallUserRestrictions() throws Exception {
592         boolean mIsWatch = hasDeviceFeature("android.hardware.type.watch");
593         if (mIsWatch) {
594             return;
595         }
596         // UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
597         final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
598         // UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
599         final String DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY =
600                 "no_install_unknown_sources_globally";
601         final String SECURE_SETTING_CATEGORY = "secure";
602         final String GLOBAL_SETTING_CATEGORY = "global";
603         final File apk = mBuildHelper.getTestFile(TEST_APP_APK);
604 
605         // Needed to access dpm.getPolicyExemptApps()
606         allowTestApiAccess(DEVICE_ADMIN_PKG);
607 
608         try {
609             // Install the test and prepare the test apk.
610             installAppAsUser(PACKAGE_INSTALLER_APK, mUserId);
611             assertTrue(getDevice().pushFile(apk, TEST_APP_LOCATION + apk.getName()));
612             setInstallPackageAppOps(PACKAGE_INSTALLER_PKG, true, mUserId);
613 
614             // Add restrictions and test if we can install the apk.
615             getDevice().uninstallPackage(TEST_APP_PKG);
616             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES, true, mUserId);
617             runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest",
618                     "testManualInstallBlocked", mUserId);
619 
620             // Clear restrictions and test if we can install the apk.
621             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES, false, mUserId);
622 
623             // Add global restriction and test if we can install the apk.
624             getDevice().uninstallPackage(TEST_APP_PKG);
625             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, true, mUserId);
626             runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest",
627                     "testManualInstallBlocked", mUserId);
628 
629             // Clear global restriction and test if we can install the apk.
630             changeUserRestrictionOrFail(DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, false, mUserId);
631             setInstallPackageAppOps(PACKAGE_INSTALLER_PKG, true, mUserId);
632             runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest",
633                     "testManualInstallSucceeded", mUserId);
634         } finally {
635             setInstallPackageAppOps(PACKAGE_INSTALLER_PKG, false, mUserId);
636             String command = "rm " + TEST_APP_LOCATION + apk.getName();
637             getDevice().executeShellCommand(command);
638             getDevice().uninstallPackage(TEST_APP_PKG);
639             getDevice().uninstallPackage(PACKAGE_INSTALLER_PKG);
640         }
641     }
642 
643     @Test
testAudioRestriction()644     public void testAudioRestriction() throws Exception {
645         // This package may need to toggle zen mode for this test, so allow it to do so.
646         allowNotificationPolicyAccess(DEVICE_ADMIN_PKG, mUserId);
647         try {
648             executeDeviceTestClass(".AudioRestrictionTest");
649         } finally {
650             disallowNotificationPolicyAccess(DEVICE_ADMIN_PKG, mUserId);
651         }
652     }
653 
654     @Test
testDisallowAdjustVolumeMutedLogged()655     public void testDisallowAdjustVolumeMutedLogged() throws Exception {
656         assertMetricsLogged(getDevice(), () -> {
657             executeDeviceTestMethod(".DevicePolicyLoggingTest",
658                     "testDisallowAdjustVolumeMutedLogged");
659         }, new DevicePolicyEventWrapper.Builder(EventId.SET_MASTER_VOLUME_MUTED_VALUE)
660                     .setAdminPackageName(DEVICE_ADMIN_PKG)
661                     .setBoolean(true)
662                     .build(),
663             new DevicePolicyEventWrapper.Builder(EventId.SET_MASTER_VOLUME_MUTED_VALUE)
664                     .setAdminPackageName(DEVICE_ADMIN_PKG)
665                     .setBoolean(false)
666                     .build());
667     }
668 
669     @LargeTest
670     @Test
671     @RequiresFlagsEnabled(Flags.FLAG_SYSTEM_SERVER_ROLE_CONTROLLER_ENABLED)
testLockTaskAfterReboot()672     public void testLockTaskAfterReboot() throws Exception {
673         try {
674             // Just start kiosk mode
675             executeDeviceTestMethod(
676                     ".LockTaskHostDrivenTest", "testStartLockTask_noAsserts");
677 
678             // Reboot while in kiosk mode and then unlock the device
679             rebootAndWaitUntilReady();
680 
681             // Check that kiosk mode is working and can't be interrupted
682             executeDeviceTestMethod(".LockTaskHostDrivenTest",
683                     "testLockTaskIsActiveAndCantBeInterrupted");
684         } finally {
685             executeDeviceTestMethod(".LockTaskHostDrivenTest", "testCleanupLockTask_noAsserts");
686         }
687     }
688 
689     @LargeTest
690     @Test
691     @Ignore("Ignored while migrating to new infrastructure b/175377361")
testLockTaskAfterReboot_tryOpeningSettings()692     public void testLockTaskAfterReboot_tryOpeningSettings() throws Exception {
693         try {
694             // Just start kiosk mode
695             executeDeviceTestMethod(
696                     ".LockTaskHostDrivenTest", "testStartLockTask_noAsserts");
697 
698             // Reboot while in kiosk mode and then unlock the device
699             rebootAndWaitUntilReady();
700 
701             // Wait for the LockTask starting
702             waitForBroadcastIdle();
703 
704             // Make sure that the LockTaskUtilityActivityIfWhitelisted was started.
705             executeDeviceTestMethod(".LockTaskHostDrivenTest", "testLockTaskIsActive");
706 
707             // Try to open settings via adb
708             executeShellCommand("am start -a android.settings.SETTINGS");
709 
710             // Check again
711             executeDeviceTestMethod(".LockTaskHostDrivenTest",
712                     "testLockTaskIsActiveAndCantBeInterrupted");
713         } finally {
714             executeDeviceTestMethod(".LockTaskHostDrivenTest", "testCleanupLockTask_noAsserts");
715         }
716     }
717 
718     @FlakyTest(bugId = 141314026)
719     @Test
testSuspendPackage()720     public void testSuspendPackage() throws Exception {
721         CLog.i("runTestSuspendPackage() on user %d", mUserId);
722 
723         installAppAsUser(INTENT_SENDER_APK, mUserId);
724         installAppAsUser(INTENT_RECEIVER_APK, mUserId);
725         assertMetricsLogged(getDevice(), () -> {
726             // Suspend a testing package.
727             executeDeviceTestMethod(".SuspendPackageTest", "testSetPackagesSuspended");
728         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PACKAGES_SUSPENDED_VALUE)
729                     .setAdminPackageName(DEVICE_ADMIN_PKG)
730                     .setStrings(INTENT_RECEIVER_PKG)
731                     .setBoolean(false)
732                     .build());
733         // Verify that the package is suspended from the PREVIOUS test and that the dialog is shown
734         executeSuspendPackageTestMethod("testPackageSuspended");
735 
736         // Undo the suspend.
737         executeDeviceTestMethod(".SuspendPackageTest", "testSetPackagesNotSuspended");
738         // Verify that the package is not suspended from the PREVIOUS test and that the app launches
739         executeSuspendPackageTestMethod("testPackageNotSuspended");
740 
741         // Verify we cannot suspend not suspendable packages.
742         executeDeviceTestMethod(".SuspendPackageTest", "testSuspendNotSuspendablePackages");
743     }
744 
745     @FlakyTest(bugId = 141314026)
746     @Test
testSuspendPackageWithPackageManager()747     public void testSuspendPackageWithPackageManager() throws Exception {
748         CLog.i("runTestSuspendPackageWithPackageManager() on user %d", mUserId);
749 
750         installAppAsUser(INTENT_SENDER_APK, mUserId);
751         installAppAsUser(INTENT_RECEIVER_APK, mUserId);
752         // Suspend a testing package with the PackageManager
753         executeDeviceTestMethod(".SuspendPackageTest",
754                 "testSetPackagesSuspendedWithPackageManager");
755         // Verify that the package is suspended from the PREVIOUS test and that the dialog is shown
756         executeSuspendPackageTestMethod("testPackageSuspendedWithPackageManager");
757 
758         // Undo the suspend.
759         executeDeviceTestMethod(".SuspendPackageTest",
760                 "testSetPackagesNotSuspendedWithPackageManager");
761         // Verify that the package is not suspended from the PREVIOUS test and that the app launches
762         executeSuspendPackageTestMethod("testPackageNotSuspended");
763     }
764     @Test
testRequiredStrongAuthTimeout()765     public void testRequiredStrongAuthTimeout() throws Exception {
766         assumeHasSecureLockScreenFeature();
767 
768         executeDeviceTestClass(".RequiredStrongAuthTimeoutTest");
769     }
770 
771     @Test
testPasswordSufficientInitially()772     public void testPasswordSufficientInitially() throws Exception {
773         executeDeviceTestClass(".PasswordSufficientInitiallyTest");
774     }
775 
776     @Test
testPasswordExpiration()777     public void testPasswordExpiration() throws Exception {
778         assumeHasSecureLockScreenFeature();
779 
780         executeDeviceTestClass(".PasswordExpirationTest");
781     }
782 
783     @Test
testGetPasswordExpiration()784     public void testGetPasswordExpiration() throws Exception {
785         assumeHasSecureLockScreenFeature();
786 
787         executeDeviceTestMethod(".GetPasswordExpirationTest",
788                 "testGetPasswordExpiration");
789         try {
790             executeDeviceTestMethod(".GetPasswordExpirationTest",
791                     "testGetPasswordExpirationUpdatedAfterPasswordReset_beforeReset");
792             // Wait for 20 seconds so we can make sure that the expiration date is refreshed later.
793             RunUtil.getDefault().sleep(20000);
794             changeUserCredential(TEST_PASSWORD, null, mUserId);
795             executeDeviceTestMethod(".GetPasswordExpirationTest",
796                     "testGetPasswordExpirationUpdatedAfterPasswordReset_afterReset");
797         } finally {
798             changeUserCredential(null, TEST_PASSWORD, mUserId);
799         }
800     }
801 
802     @Test
testPasswordQualityWithoutSecureLockScreen()803     public void testPasswordQualityWithoutSecureLockScreen() throws Exception {
804         assumeDoesNotHaveSecureLockScreenFeature();
805 
806         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UnavailableSecureLockScreenTest", mUserId);
807     }
808 
809     @Test
testSetSystemSetting()810     public void testSetSystemSetting() throws Exception {
811         executeDeviceTestClass(".SetSystemSettingTest");
812     }
813 
814     @TemporarilyIgnoreOnHeadlessSystemUserMode(bugId = "197859595",
815             reason = "Will be migrated to new test infra")
816     @Test
testKeyManagement()817     public void testKeyManagement() throws Exception {
818         installAppAsUser(SHARED_UID_APP1_APK, mUserId);
819         installAppAsUser(SHARED_UID_APP2_APK, mUserId);
820 
821         executeDeviceTestClass(".KeyManagementTest");
822     }
823 
824     @TemporarilyIgnoreOnHeadlessSystemUserMode(bugId = "197859595",
825             reason = "Will be migrated to new test infra")
826     @Test
827     // TODO(b/198408853): Migrate
testGenerateKeyPairLogged()828     public void testGenerateKeyPairLogged() throws Exception {
829         assumeTrue(mHasAttestation);
830 
831         assertMetricsLogged(getDevice(), () -> {
832                 executeDeviceTestMethod(
833                         ".KeyManagementTest", "testCanGenerateKeyPairWithKeyAttestation");
834                 }, new DevicePolicyEventWrapper.Builder(EventId.GENERATE_KEY_PAIR_VALUE)
835                 .setAdminPackageName(DEVICE_ADMIN_PKG)
836                 .setBoolean(false)
837                 .setInt(0)
838                 .setStrings("RSA", "notCredentialManagementApp")
839                 .build(),
840                 new DevicePolicyEventWrapper.Builder(EventId.GENERATE_KEY_PAIR_VALUE)
841                 .setAdminPackageName(DEVICE_ADMIN_PKG)
842                 .setBoolean(false)
843                 .setInt(0)
844                 .setStrings("EC", "notCredentialManagementApp")
845                 .build());
846 
847     }
848 
849     @Test
testSetKeyPairCertificateLogged()850     public void testSetKeyPairCertificateLogged() throws Exception {
851         assertMetricsLogged(getDevice(), () -> {
852                 executeDeviceTestMethod(".KeyManagementTest", "testCanSetKeyPairCert");
853                 }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEY_PAIR_CERTIFICATE_VALUE)
854                 .setAdminPackageName(DEVICE_ADMIN_PKG)
855                 .setBoolean(false)
856                 .setStrings("notCredentialManagementApp")
857                 .build());
858     }
859 
860     @Test
testPermittedInputMethods()861     public void testPermittedInputMethods() throws Exception {
862         executeDeviceTestMethod(".InputMethodsTest", "testPermittedInputMethodsThrowsIfWrongAdmin");
863         assertMetricsLogged(getDevice(), () -> {
864             executeDeviceTestMethod(".InputMethodsTest", "testPermittedInputMethods");
865         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
866                 .setAdminPackageName(DEVICE_ADMIN_PKG)
867                 .setStrings(NOT_CALLED_FROM_PARENT, new String[0])
868                 .build(),
869         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
870                 .setAdminPackageName(DEVICE_ADMIN_PKG)
871                 .setStrings(NOT_CALLED_FROM_PARENT, new String[0])
872                 .build(),
873         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
874                 .setAdminPackageName(DEVICE_ADMIN_PKG)
875                 .setStrings(NOT_CALLED_FROM_PARENT, "com.google.pkg.one", "com.google.pkg.two")
876                 .build());
877     }
878 
879     @Test
testSetKeyguardDisabledFeaturesLogged()880     public void testSetKeyguardDisabledFeaturesLogged() throws Exception {
881         assertMetricsLogged(getDevice(), () -> {
882             executeDeviceTestMethod(
883                     ".DevicePolicyLoggingTest", "testSetKeyguardDisabledFeaturesLogged");
884         }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
885                     .setAdminPackageName(DEVICE_ADMIN_PKG)
886                     .setInt(KEYGUARD_DISABLE_FEATURES_NONE)
887                     .setStrings(NOT_CALLED_FROM_PARENT)
888                     .build(),
889             new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
890                     .setAdminPackageName(DEVICE_ADMIN_PKG)
891                     .setInt(KEYGUARD_DISABLE_FINGERPRINT)
892                     .setStrings(NOT_CALLED_FROM_PARENT)
893                     .build(),
894             new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
895                     .setAdminPackageName(DEVICE_ADMIN_PKG)
896                     .setInt(KEYGUARD_DISABLE_TRUST_AGENTS)
897                     .setStrings(NOT_CALLED_FROM_PARENT)
898                     .build(),
899             new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
900                     .setAdminPackageName(DEVICE_ADMIN_PKG)
901                     .setInt(KEYGUARD_DISABLE_FEATURES_NONE)
902                     .setStrings(NOT_CALLED_FROM_PARENT)
903                     .build());
904     }
905 
906     @Test
testSetKeyguardDisabledSecureCameraLogged()907     public void testSetKeyguardDisabledSecureCameraLogged() throws Exception {
908         assertMetricsLogged(getDevice(), () -> {
909             executeDeviceTestMethod(
910                     ".DevicePolicyLoggingTest", "testSetKeyguardDisabledSecureCameraLogged");
911         }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_FEATURES_VALUE)
912                 .setAdminPackageName(DEVICE_ADMIN_PKG)
913                 .setInt(KEYGUARD_DISABLE_SECURE_CAMERA)
914                 .setStrings(NOT_CALLED_FROM_PARENT)
915                 .build());
916     }
917 
918     @Test
testSetUserRestrictionLogged()919     public void testSetUserRestrictionLogged() throws Exception {
920         assertMetricsLogged(getDevice(), () -> {
921             executeDeviceTestMethod(
922                     ".DevicePolicyLoggingTest", "testSetUserRestrictionLogged");
923         }, new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
924                     .setAdminPackageName(DEVICE_ADMIN_PKG)
925                     .setStrings(DISALLOW_CONFIG_LOCATION, NOT_CALLED_FROM_PARENT)
926                     .build(),
927             new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
928                     .setAdminPackageName(DEVICE_ADMIN_PKG)
929                     .setStrings(DISALLOW_CONFIG_LOCATION, NOT_CALLED_FROM_PARENT)
930                     .build(),
931             new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
932                     .setAdminPackageName(DEVICE_ADMIN_PKG)
933                     .setStrings(DISALLOW_ADJUST_VOLUME, NOT_CALLED_FROM_PARENT)
934                     .build(),
935             new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
936                     .setAdminPackageName(DEVICE_ADMIN_PKG)
937                     .setStrings(DISALLOW_ADJUST_VOLUME, NOT_CALLED_FROM_PARENT)
938                     .build(),
939             new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
940                     .setAdminPackageName(DEVICE_ADMIN_PKG)
941                     .setStrings(DISALLOW_AUTOFILL, NOT_CALLED_FROM_PARENT)
942                     .build(),
943             new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
944                     .setAdminPackageName(DEVICE_ADMIN_PKG)
945                     .setStrings(DISALLOW_AUTOFILL, NOT_CALLED_FROM_PARENT)
946                     .build()
947         );
948     }
949 
950     @Test
testSetSecureSettingLogged()951     public void testSetSecureSettingLogged() throws Exception {
952         assertMetricsLogged(getDevice(), () -> {
953             executeDeviceTestMethod(
954                     ".DevicePolicyLoggingTest", "testSetSecureSettingLogged");
955         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
956                 .setAdminPackageName(DEVICE_ADMIN_PKG)
957                 .setStrings(SKIP_FIRST_USE_HINTS, "1")
958                 .build(),
959             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
960                     .setAdminPackageName(DEVICE_ADMIN_PKG)
961                     .setStrings(SKIP_FIRST_USE_HINTS, "0")
962                     .build(),
963             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
964                     .setAdminPackageName(DEVICE_ADMIN_PKG)
965                     .setStrings(DEFAULT_INPUT_METHOD, "com.example.input")
966                     .build()
967                     ,
968             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURE_SETTING_VALUE)
969                     .setAdminPackageName(DEVICE_ADMIN_PKG)
970                     .setStrings(DEFAULT_INPUT_METHOD)
971                     .build());
972     }
973 
974     @Test
testSetPermissionPolicyLogged()975     public void testSetPermissionPolicyLogged() throws Exception {
976         assertMetricsLogged(getDevice(), () -> {
977             executeDeviceTestMethod(
978                     ".DevicePolicyLoggingTest", "testSetPermissionPolicyLogged");
979         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_POLICY_VALUE)
980                 .setAdminPackageName(DEVICE_ADMIN_PKG)
981                 .setInt(PERMISSION_POLICY_AUTO_DENY)
982                 .setBoolean(false)
983                 .build(),
984         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_POLICY_VALUE)
985                 .setAdminPackageName(DEVICE_ADMIN_PKG)
986                 .setInt(PERMISSION_POLICY_AUTO_GRANT)
987                 .setBoolean(false)
988                 .build(),
989         new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_POLICY_VALUE)
990                 .setAdminPackageName(DEVICE_ADMIN_PKG)
991                 .setInt(PERMISSION_POLICY_PROMPT)
992                 .setBoolean(false)
993                 .build());
994     }
995 
996     @Test
testSetPermissionGrantStateLogged()997     public void testSetPermissionGrantStateLogged() throws Exception {
998         installAppPermissionAppAsUser();
999         assertMetricsLogged(getDevice(), () -> {
1000             executeDeviceTestMethod(
1001                     ".DevicePolicyLoggingTest", "testSetPermissionGrantStateLogged");
1002         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_GRANT_STATE_VALUE)
1003                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1004                     .setInt(PERMISSION_GRANT_STATE_GRANTED)
1005                     .setBoolean(false)
1006                     .setStrings("android.permission.READ_CONTACTS")
1007                     .build(),
1008             new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_GRANT_STATE_VALUE)
1009                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1010                     .setInt(PERMISSION_GRANT_STATE_DENIED)
1011                     .setBoolean(false)
1012                     .setStrings("android.permission.READ_CONTACTS")
1013                     .build(),
1014             new DevicePolicyEventWrapper.Builder(EventId.SET_PERMISSION_GRANT_STATE_VALUE)
1015                     .setAdminPackageName(DEVICE_ADMIN_PKG)
1016                     .setInt(PERMISSION_GRANT_STATE_DEFAULT)
1017                     .setBoolean(false)
1018                     .setStrings("android.permission.READ_CONTACTS")
1019                     .build());
1020     }
1021 
1022     @Test
testEnableSystemAppWithIntentLogged()1023     public void testEnableSystemAppWithIntentLogged() throws Exception {
1024         final String systemPackageToEnable = getLaunchableSystemPackage();
1025         if (systemPackageToEnable == null) {
1026             return;
1027         }
1028         final Map<String, String> params =
1029                 ImmutableMap.of(PARAM_APP_TO_ENABLE, systemPackageToEnable);
1030         assertMetricsLogged(getDevice(), () -> {
1031             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DevicePolicyLoggingTest",
1032                     "testEnableSystemAppWithIntentLogged", mUserId, params);
1033         }, new DevicePolicyEventWrapper.Builder(EventId.ENABLE_SYSTEM_APP_WITH_INTENT_VALUE)
1034                 .setAdminPackageName(DEVICE_ADMIN_PKG)
1035                 .setBoolean(false)
1036                 .setStrings("android.intent.action.MAIN")
1037                 .build());
1038     }
1039 
1040     @Test
testIsDeviceOrganizationOwnedWithManagedProfile()1041     public void testIsDeviceOrganizationOwnedWithManagedProfile() throws Exception {
1042         executeDeviceTestMethod(".DeviceOwnershipTest",
1043                 "testCallingIsOrganizationOwnedWithManagedProfileExpectingFalse");
1044     }
1045 
1046     @LockSettingsTest
1047     @Test
testSecondaryLockscreen()1048     public void testSecondaryLockscreen() throws Exception {
1049         executeDeviceTestClass(".SecondaryLockscreenTest");
1050     }
1051 
getLaunchableSystemPackage()1052     private String getLaunchableSystemPackage() throws DeviceNotAvailableException {
1053         final List<String> enabledSystemPackageNames = getEnabledSystemPackageNames();
1054         for (String enabledSystemPackage : enabledSystemPackageNames) {
1055             if (enabledSystemPackage.equals("com.android.inputmethod.latin")) {
1056                 // com.android.inputmethod.latin package disables its launcher activity upon
1057                 // installation so not a suitable candidate for a launchable package.
1058                 continue;
1059             }
1060             final String result = getDevice().executeShellCommand(
1061                     String.format(RESOLVE_ACTIVITY_CMD, mUserId, enabledSystemPackage));
1062             if (!result.contains("No activity found")) {
1063                 return enabledSystemPackage;
1064             }
1065         }
1066         return null;
1067     }
1068 
getEnabledSystemPackageNames()1069     private List<String> getEnabledSystemPackageNames() throws DeviceNotAvailableException {
1070         final String commandResult =
1071                 getDevice().executeShellCommand("pm list packages -e -s --user " + mUserId);
1072         final int prefixLength = "package:".length();
1073         return new ArrayList<>(Arrays.asList(commandResult.split("\n")))
1074                 .stream()
1075                 .map(line -> line.substring(prefixLength))
1076                 .collect(Collectors.toList());
1077     }
1078 
1079     @Test
testAdminControlOverSensorPermissionGrantsDefault()1080     public void testAdminControlOverSensorPermissionGrantsDefault() throws Exception {
1081         // By default, admin should not be able to grant sensors-related permissions.
1082         executeDeviceTestMethod(".SensorPermissionGrantTest",
1083                 "testAdminCannotGrantSensorsPermission");
1084     }
1085 
1086     /**
1087      * Executes a test class on device. Prior to running, turn off background data usage
1088      * restrictions, and restore the original restrictions after the test.
1089      */
executeDeviceTestClassNoRestrictBackground(String className, int userId)1090     private void executeDeviceTestClassNoRestrictBackground(String className, int userId)
1091             throws Exception {
1092         boolean originalRestriction = ensureRestrictBackgroundPolicyOff();
1093         try {
1094             executeDeviceTestClass(className, userId);
1095         } finally {
1096             // if the test throws exception, still restore the policy
1097             restoreRestrictBackgroundPolicyTo(originalRestriction);
1098         }
1099     }
1100 
executeDeviceTestClass(String className)1101     protected void executeDeviceTestClass(String className) throws Exception {
1102         executeDeviceTestMethod(className, /* testName= */ null);
1103     }
1104 
executeDeviceTestClass(String className, int userId)1105     protected void executeDeviceTestClass(String className, int userId) throws Exception {
1106         executeDeviceTestMethod(className, /* testName= */ null, userId);
1107     }
1108 
executeDeviceTestMethod(String className, String testName)1109     protected void executeDeviceTestMethod(String className, String testName) throws Exception {
1110         executeDeviceTestMethod(className, testName, /* params= */ new HashMap<>());
1111     }
1112 
executeDeviceTestMethod(String className, String testName, int userId)1113     protected void executeDeviceTestMethod(String className, String testName, int userId)
1114             throws Exception {
1115         executeDeviceTestMethod(className, testName, userId, /* params= */ new HashMap<>());
1116     }
1117 
executeDeviceTestMethod(String className, String testName, Map<String, String> params)1118     protected void executeDeviceTestMethod(String className, String testName,
1119             Map<String, String> params) throws Exception {
1120         executeDeviceTestMethod(className, testName, mUserId, params);
1121     }
1122 
executeDeviceTestMethod(String className, String testName, int userId, Map<String, String> params)1123     protected void executeDeviceTestMethod(String className, String testName, int userId,
1124             Map<String, String> params) throws Exception {
1125         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, testName, userId, params);
1126     }
1127 
installAppPermissionAppAsUser()1128     protected void installAppPermissionAppAsUser()
1129             throws FileNotFoundException, DeviceNotAvailableException {
1130         installAppPermissionAppAsUser(mUserId);
1131     }
1132 
installAppPermissionAppAsUser(int userId)1133     protected final void installAppPermissionAppAsUser(int userId)
1134             throws FileNotFoundException, DeviceNotAvailableException {
1135         installAppAsUser(PERMISSIONS_APP_APK, false, userId);
1136     }
1137 
executeSuspendPackageTestMethod(String testName)1138     private void executeSuspendPackageTestMethod(String testName) throws Exception {
1139         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".SuspendPackageTest", testName, mUserId);
1140     }
1141 
changeUserRestrictionOrFail(String key, boolean value, int userId)1142     private void changeUserRestrictionOrFail(String key, boolean value, int userId)
1143             throws DeviceNotAvailableException {
1144         changeUserRestrictionOrFail(key, value, userId, DEVICE_ADMIN_PKG);
1145     }
1146 
setDelegatedScopes(String packageName, List<String> scopes)1147     protected void setDelegatedScopes(String packageName, List<String> scopes)
1148             throws DeviceNotAvailableException {
1149         final String packageNameExtra = "--es extra-package-name " + packageName;
1150         String scopesExtra = "";
1151         if (scopes != null && scopes.size() > 0) {
1152             scopesExtra = "--esa extra-scopes-list " + scopes.get(0);
1153             for (int i = 1; i < scopes.size(); ++i) {
1154                 scopesExtra += "," + scopes.get(i);
1155             }
1156         }
1157         final String extras = packageNameExtra + " " + scopesExtra;
1158 
1159         changePolicyOrFail("set-delegated-scopes", extras, mUserId);
1160     }
1161 
setInstallPackageAppOps(String packageName, boolean allowed, int userId)1162     private void setInstallPackageAppOps(String packageName, boolean allowed, int userId)
1163             throws DeviceNotAvailableException {
1164         String command = "appops set --user " + userId + " " + packageName + " " +
1165                 "REQUEST_INSTALL_PACKAGES "
1166                 + (allowed ? "allow" : "default");
1167         CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
1168     }
1169 
changePolicyOrFail(String command, String extras, int userId)1170     private void changePolicyOrFail(String command, String extras, int userId)
1171             throws DeviceNotAvailableException {
1172         changePolicyOrFail(command, extras, userId, DEVICE_ADMIN_PKG);
1173     }
1174 
1175     /**
1176      * Start SimpleActivity synchronously in a particular user.
1177      */
startSimpleActivityAsUser(int userId)1178     protected void startSimpleActivityAsUser(int userId) throws Exception {
1179         installAppAsUser(TEST_APP_APK, /* grantPermissions */ true, /* dontKillApp */ true, userId);
1180         startActivityAsUser(userId, TEST_APP_PKG, TEST_APP_PKG + ".SimpleActivity");
1181     }
1182 
setScreenCaptureDisabled_assist(int userId, boolean disabled)1183     protected void setScreenCaptureDisabled_assist(int userId, boolean disabled) throws Exception {
1184         // Set the policy.
1185         String testMethodName = disabled
1186                 ? "testSetScreenCaptureDisabled_true"
1187                 : "testSetScreenCaptureDisabled_false";
1188         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
1189         testMethodName = disabled
1190                 ? "testScreenCaptureImpossible_assist"
1191                 : "testScreenCapturePossible_assist";
1192 
1193         // Check whether the VoiceInteractionService can retrieve the screenshot.
1194         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
1195 
1196         if (userId == mPrimaryUserId) {
1197             // If testing for user-0, also make sure the existing screen can't be captured.
1198             runDeviceTestsAsUser(
1199                     DEVICE_ADMIN_PKG,
1200                     ".AssistScreenCaptureDisabledTest",
1201                     testMethodName,
1202                     mPrimaryUserId);
1203         }
1204 
1205         // Make sure the foreground activity is from the target user.
1206         startSimpleActivityAsUser(userId);
1207 
1208         runDeviceTestsAsUser(
1209                 DEVICE_ADMIN_PKG,
1210                 ".AssistScreenCaptureDisabledTest",
1211                 testMethodName,
1212                 mPrimaryUserId);
1213     }
1214 
1215     /**
1216      * Allows packageName to manage notification policy configuration, which
1217      * includes toggling zen mode.
1218      */
allowNotificationPolicyAccess(String packageName, int userId)1219     private void allowNotificationPolicyAccess(String packageName, int userId)
1220             throws DeviceNotAvailableException {
1221         List<String> enabledPackages = getEnabledNotificationPolicyPackages(userId);
1222         if (!enabledPackages.contains(packageName)) {
1223             enabledPackages.add(packageName);
1224             setEnabledNotificationPolicyPackages(enabledPackages, userId);
1225         }
1226     }
1227 
1228     /**
1229      * Disallows packageName to manage notification policy configuration, which
1230      * includes toggling zen mode.
1231      */
disallowNotificationPolicyAccess(String packageName, int userId)1232     private void disallowNotificationPolicyAccess(String packageName, int userId)
1233             throws DeviceNotAvailableException {
1234         List<String> enabledPackages = getEnabledNotificationPolicyPackages(userId);
1235         if (enabledPackages.contains(packageName)) {
1236             enabledPackages.remove(packageName);
1237             setEnabledNotificationPolicyPackages(enabledPackages, userId);
1238         }
1239     }
1240 
setEnabledNotificationPolicyPackages(List<String> packages, int userId)1241     private void setEnabledNotificationPolicyPackages(List<String> packages, int userId)
1242             throws DeviceNotAvailableException {
1243         getDevice().setSetting(userId, "secure", ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
1244                 String.join(":", packages));
1245     }
1246 
getEnabledNotificationPolicyPackages(int userId)1247     private List<String> getEnabledNotificationPolicyPackages(int userId)
1248             throws DeviceNotAvailableException {
1249         String settingValue = getDevice().getSetting(userId, "secure",
1250                 ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
1251         if (settingValue == null) {
1252             return new ArrayList<String>();
1253         }
1254         return new ArrayList<String>(Arrays.asList(settingValue.split(":|\n")));
1255     }
1256 
setVoiceInteractionService(String componentName)1257     protected void setVoiceInteractionService(String componentName)
1258             throws DeviceNotAvailableException {
1259         getDevice().setSetting(
1260                 mPrimaryUserId, "secure", "voice_interaction_service", componentName);
1261         getDevice().setSetting(mPrimaryUserId, "secure", "assist_structure_enabled", "1");
1262         getDevice().setSetting(mPrimaryUserId, "secure", "assist_screenshot_enabled", "1");
1263     }
1264 
clearVoiceInteractionService()1265     protected void clearVoiceInteractionService() throws DeviceNotAvailableException {
1266         getDevice().executeShellCommand("settings delete secure voice_interaction_service");
1267     }
1268 
1269     /**
1270      * Ensure that restrict background policy is off.
1271      * Returns the original status of restrict background policy.
1272      */
ensureRestrictBackgroundPolicyOff()1273     private boolean ensureRestrictBackgroundPolicyOff() throws Exception {
1274         String restriction = getDevice().executeShellCommand(RESTRICT_BACKGROUND_GET_CMD);
1275         if (restriction.contains("enabled")) {
1276             getDevice().executeShellCommand(RESTRICT_BACKGROUND_OFF_CMD);
1277             return true;
1278         }
1279         return false;
1280     }
1281 
restoreRestrictBackgroundPolicyTo(boolean restricted)1282     private void restoreRestrictBackgroundPolicyTo(boolean restricted) throws Exception {
1283         getDevice().executeShellCommand(
1284                 restricted ? RESTRICT_BACKGROUND_ON_CMD : RESTRICT_BACKGROUND_OFF_CMD);
1285     }
1286 
assumeIsNotWatch()1287     private void assumeIsNotWatch() throws Exception {
1288         assumeFalse("is watch", hasDeviceFeature("android.hardware.type.watch"));
1289     }
1290 }
1291