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