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