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