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.fail;
22 
23 import android.platform.test.annotations.FlakyTest;
24 import android.platform.test.annotations.LargeTest;
25 import android.stats.devicepolicy.EventId;
26 
27 import com.android.cts.devicepolicy.DeviceAdminFeaturesCheckerRule.IgnoreOnHeadlessSystemUserMode;
28 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
29 import com.android.tradefed.device.DeviceNotAvailableException;
30 import com.android.tradefed.log.LogUtil.CLog;
31 
32 import com.google.common.collect.ImmutableMap;
33 
34 import org.junit.Ignore;
35 import org.junit.Test;
36 
37 import java.util.ArrayList;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 
43 /**
44  * Set of tests for device owner use cases that also apply to profile owners.
45  * Tests that should be run identically in both cases are added in DeviceAndProfileOwnerTest.
46  */
47 public final class MixedDeviceOwnerTest extends DeviceAndProfileOwnerTest {
48 
49     private static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
50     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
51 
52     private static final String ARG_SECURITY_LOGGING_BATCH_NUMBER = "batchNumber";
53     private static final int SECURITY_EVENTS_BATCH_SIZE = 100;
54 
55     private boolean mDeviceOwnerSet;
56 
57     @Override
setUp()58     public void setUp() throws Exception {
59         super.setUp();
60 
61         mUserId = mPrimaryUserId;
62 
63         CLog.i("%s.setUp(): mUserId=%d, mPrimaryUserId=%d, mInitialUserId=%d, "
64                 + "mDeviceOwnerUserId=%d", getClass(), mUserId, mPrimaryUserId, mInitialUserId,
65                 mDeviceOwnerUserId);
66 
67         installDeviceOwnerApp(DEVICE_ADMIN_APK);
68         mDeviceOwnerSet = setDeviceOwner(DEVICE_ADMIN_COMPONENT_FLATTENED, mDeviceOwnerUserId,
69                 /*expectFailure= */ false);
70 
71         if (!mDeviceOwnerSet) {
72             removeDeviceOwnerAdmin(DEVICE_ADMIN_COMPONENT_FLATTENED);
73             getDevice().uninstallPackage(DEVICE_ADMIN_PKG);
74             fail("Failed to set device owner on user " + mDeviceOwnerUserId);
75         }
76         if (isHeadlessSystemUserMode()) {
77             affiliateUsers(DEVICE_ADMIN_PKG, mDeviceOwnerUserId, mPrimaryUserId);
78         }
79     }
80 
81     @Override
tearDown()82     public void tearDown() throws Exception {
83         if (mDeviceOwnerSet) {
84             removeDeviceOwnerAdmin(DEVICE_ADMIN_COMPONENT_FLATTENED);
85         }
86 
87         super.tearDown();
88     }
89 
90     @Test
testLockTask_unaffiliatedUser()91     public void testLockTask_unaffiliatedUser() throws Exception {
92         assumeCanCreateAdditionalUsers(1);
93 
94         final int userId = createSecondaryUserAsProfileOwner();
95         runDeviceTestsAsUser(
96                 DEVICE_ADMIN_PKG,
97                 ".AffiliationTest",
98                 "testLockTaskMethodsThrowExceptionIfUnaffiliated",
99                 userId);
100 
101         setUserAsAffiliatedUserToPrimary(userId);
102         runDeviceTestsAsUser(
103                 DEVICE_ADMIN_PKG,
104                 ".AffiliationTest",
105                 "testSetLockTaskPackagesClearedIfUserBecomesUnaffiliated",
106                 userId);
107     }
108 
109     @Test
testDelegatedCertInstallerDeviceIdAttestation()110     public void testDelegatedCertInstallerDeviceIdAttestation() throws Exception {
111         setUpDelegatedCertInstallerAndRunTests(() ->
112                 runDeviceTestsAsUser("com.android.cts.certinstaller",
113                         ".DelegatedDeviceIdAttestationTest",
114                         "testGenerateKeyPairWithDeviceIdAttestationExpectingSuccess", mUserId));
115     }
116 
117     @FlakyTest
118     @Override
119     @Test
testCaCertManagement()120     public void testCaCertManagement() throws Exception {
121         super.testCaCertManagement();
122     }
123 
124     @FlakyTest(bugId = 141161038)
125     @Override
126     @Test
testCannotRemoveUserIfRestrictionSet()127     public void testCannotRemoveUserIfRestrictionSet() throws Exception {
128         super.testCannotRemoveUserIfRestrictionSet();
129     }
130 
131     @FlakyTest
132     @Override
133     @Test
testInstallCaCertLogged()134     public void testInstallCaCertLogged() throws Exception {
135         super.testInstallCaCertLogged();
136     }
137 
138     @FlakyTest(bugId = 137088260)
139     @Test
testWifi()140     public void testWifi() throws Exception {
141         assumeHasWifiFeature();
142 
143         executeDeviceTestMethod(".WifiTest", "testGetWifiMacAddress");
144         assertMetricsLogged(getDevice(), () -> {
145             executeDeviceTestMethod(".WifiTest", "testGetWifiMacAddress");
146         }, new DevicePolicyEventWrapper.Builder(EventId.GET_WIFI_MAC_ADDRESS_VALUE)
147                 .setAdminPackageName(DEVICE_ADMIN_PKG)
148                 .build());
149     }
150 
151     @Test
testAdminConfiguredNetworks()152     public void testAdminConfiguredNetworks() throws Exception {
153         executeDeviceTestClass(".AdminConfiguredNetworksTest");
154     }
155 
156     @Override
157     @Test
158     @IgnoreOnHeadlessSystemUserMode(
159             reason = "Per-user application restriction is not applicable for headless user")
testApplicationRestrictions()160     public void testApplicationRestrictions() throws Exception {
161         super.testApplicationRestrictions();
162     }
163 
164     @Test
testSetTime()165     public void testSetTime() throws Exception {
166         assertMetricsLogged(getDevice(), () -> {
167             executeDeviceTestMethod(".TimeManagementTest", "testSetTime");
168         }, new DevicePolicyEventWrapper.Builder(EventId.SET_TIME_VALUE)
169                 .setAdminPackageName(DEVICE_ADMIN_PKG)
170                 .build());
171 
172         executeDeviceTestMethod(".TimeManagementTest", "testSetTime_failWhenAutoTimeEnabled");
173     }
174 
175     @Test
testSetTimeZone()176     public void testSetTimeZone() throws Exception {
177         assertMetricsLogged(getDevice(), () -> {
178             executeDeviceTestMethod(".TimeManagementTest", "testSetTimeZone");
179         }, new DevicePolicyEventWrapper.Builder(EventId.SET_TIME_ZONE_VALUE)
180                 .setAdminPackageName(DEVICE_ADMIN_PKG)
181                 .build());
182 
183         executeDeviceTestMethod(".TimeManagementTest", "testSetTimeZone_failIfAutoTimeZoneEnabled");
184     }
185 
getAdditionalDelegationTests()186     Map<String, DevicePolicyEventWrapper[]> getAdditionalDelegationTests() {
187         final Map<String, DevicePolicyEventWrapper[]> result = new HashMap<>();
188         DevicePolicyEventWrapper[] expectedMetrics = new DevicePolicyEventWrapper[] {
189                 new DevicePolicyEventWrapper.Builder(EventId.SET_NETWORK_LOGGING_ENABLED_VALUE)
190                         .setAdminPackageName(DELEGATE_APP_PKG)
191                         .setBoolean(true)
192                         .setInt(1)
193                         .setStrings(LOG_TAG_DEVICE_OWNER)
194                         .build(),
195                 new DevicePolicyEventWrapper.Builder(EventId.RETRIEVE_NETWORK_LOGS_VALUE)
196                         .setAdminPackageName(DELEGATE_APP_PKG)
197                         .setBoolean(true)
198                         .setStrings(LOG_TAG_DEVICE_OWNER)
199                         .build(),
200                 new DevicePolicyEventWrapper.Builder(EventId.SET_NETWORK_LOGGING_ENABLED_VALUE)
201                         .setAdminPackageName(DELEGATE_APP_PKG)
202                         .setBoolean(true)
203                         .setInt(0)
204                         .setStrings(LOG_TAG_DEVICE_OWNER)
205                         .build(),
206         };
207         result.put(".NetworkLoggingDelegateTest", expectedMetrics);
208         return result;
209     }
210 
211     @Override
getAdditionalDelegationScopes()212     List<String> getAdditionalDelegationScopes() {
213         final List<String> result = new ArrayList<>();
214         result.add(DELEGATION_NETWORK_LOGGING);
215         return result;
216     }
217 
218     @Test
testLockScreenInfo()219     public void testLockScreenInfo() throws Exception {
220         executeDeviceTestClass(".LockScreenInfoTest");
221 
222         assertMetricsLogged(getDevice(), () -> {
223             executeDeviceTestMethod(".LockScreenInfoTest", "testSetAndGetLockInfo");
224         }, new DevicePolicyEventWrapper.Builder(EventId.SET_DEVICE_OWNER_LOCK_SCREEN_INFO_VALUE)
225                 .setAdminPackageName(DEVICE_ADMIN_PKG)
226                 .build());
227     }
228 
229     @Test
testFactoryResetProtectionPolicy()230     public void testFactoryResetProtectionPolicy() throws Exception {
231         try {
232             executeDeviceTestMethod(".DeviceFeatureUtils", "testHasFactoryResetProtectionPolicy");
233         } catch (AssertionError e) {
234             // Unable to continue running tests because factory reset protection policy is not
235             // supported on the device
236             return;
237         } catch (Exception e) {
238             // Also skip test in case of other exceptions
239             return;
240         }
241 
242         assertMetricsLogged(getDevice(), () -> {
243             executeDeviceTestClass(".FactoryResetProtectionPolicyTest");
244         }, new DevicePolicyEventWrapper.Builder(EventId.SET_FACTORY_RESET_PROTECTION_VALUE)
245                 .setAdminPackageName(DEVICE_ADMIN_PKG)
246                 .build());
247     }
248 
249     @Test
testCommonCriteriaMode()250     public void testCommonCriteriaMode() throws Exception {
251         executeDeviceTestClass(".CommonCriteriaModeTest");
252     }
253 
254     @LargeTest
255     @Test
256     @Ignore("b/145932189")
testSystemUpdatePolicy()257     public void testSystemUpdatePolicy() throws Exception {
258         executeDeviceTestClass(".systemupdate.SystemUpdatePolicyTest");
259     }
260 
261     @Test
testInstallUpdate()262     public void testInstallUpdate() throws Exception {
263         pushUpdateFileToDevice("notZip.zi");
264         pushUpdateFileToDevice("empty.zip");
265         pushUpdateFileToDevice("wrongPayload.zip");
266         pushUpdateFileToDevice("wrongHash.zip");
267         pushUpdateFileToDevice("wrongSize.zip");
268 
269         executeInstallUpdateTest(/* testName= */ null);
270     }
271 
272     @Test
testInstallUpdateLogged()273     public void testInstallUpdateLogged() throws Exception {
274         assumeIsDeviceAb();
275 
276         pushUpdateFileToDevice("wrongHash.zip");
277         assertMetricsLogged(getDevice(), () -> {
278             executeInstallUpdateTest("testInstallUpdate_failWrongHash");
279         }, new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_VALUE)
280                     .setAdminPackageName(DEVICE_ADMIN_PKG)
281                     .setBoolean(/* isDeviceAb */ true)
282                     .build(),
283             new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_ERROR_VALUE)
284                     .setInt(UPDATE_ERROR_UPDATE_FILE_INVALID)
285                     .build());
286     }
287 
executeInstallUpdateTest(String testName)288     private void executeInstallUpdateTest(String testName) throws Exception {
289         // This test must run on system user as it calls installSystemUpdate(), which takes a
290         // Runnable callback (InstallSystemUpdateCallback) and hence it cannot be easily passed
291         // around through IPC (on headless system user mode).
292         executeDeviceTestMethodOnDeviceOwnerUser(".systemupdate.InstallUpdateTest", testName);
293     }
294 
295     @Test
testSecurityLoggingWithSingleUser()296     public void testSecurityLoggingWithSingleUser() throws Exception {
297         // Backup stay awake setting because testGenerateLogs() will turn it off.
298         final String stayAwake = getDevice().getSetting("global", "stay_on_while_plugged_in");
299         try {
300             // Turn logging on.
301             executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
302             // Reboot to ensure ro.device_owner is set to true in logd and logging is on.
303             rebootAndWaitUntilReady();
304             waitForUserUnlock(mUserId);
305 
306             // Generate various types of events on device side and check that they are logged.
307             executeDeviceTestMethod(".SecurityLoggingTest", "testGenerateLogs");
308             getDevice().executeShellCommand("whoami"); // Generate adb command securty event
309             executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyGeneratedLogs");
310 
311             // Reboot the device, so the security event ids are reset.
312             rebootAndWaitUntilReady();
313 
314             // Verify event ids are consistent across a consecutive batch.
315             for (int batchNumber = 0; batchNumber < 3; batchNumber++) {
316                 generateTestSecurityLogs();
317                 executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyLogIds",
318                         Collections.singletonMap(ARG_SECURITY_LOGGING_BATCH_NUMBER,
319                                 Integer.toString(batchNumber)));
320             }
321 
322             // Immediately attempting to fetch events again should fail.
323             executeDeviceTestMethod(".SecurityLoggingTest",
324                     "testSecurityLoggingRetrievalRateLimited");
325         } finally {
326             // Turn logging off.
327             executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
328             // Restore stay awake setting.
329             if (stayAwake != null) {
330                 getDevice().setSetting("global", "stay_on_while_plugged_in", stayAwake);
331             }
332         }
333     }
334 
335     @Test
testSecurityLoggingEnabledLogged()336     public void testSecurityLoggingEnabledLogged() throws Exception {
337         assertMetricsLogged(getDevice(), () -> {
338             executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
339             executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
340         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SECURITY_LOGGING_ENABLED_VALUE)
341                 .setAdminPackageName(DEVICE_ADMIN_PKG)
342                 .setBoolean(true)
343                 .build(),
344             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURITY_LOGGING_ENABLED_VALUE)
345                     .setAdminPackageName(DEVICE_ADMIN_PKG)
346                     .setBoolean(false)
347                     .build());
348     }
349 
350     @Test
testSecurityLoggingWithTwoUsers()351     public void testSecurityLoggingWithTwoUsers() throws Exception {
352         assumeCanCreateAdditionalUsers(1);
353 
354         final int userId = createUser();
355         try {
356             // The feature can be enabled, but in a "paused" state. Attempting to retrieve logs
357             // should throw security exception.
358             executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
359             executeDeviceTestMethod(".SecurityLoggingTest",
360                     "testRetrievingSecurityLogsThrowsSecurityException");
361             executeDeviceTestMethod(".SecurityLoggingTest",
362                     "testRetrievingPreviousSecurityLogsThrowsSecurityException");
363         } finally {
364             removeUser(userId);
365             executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
366         }
367     }
368 
369     @Test
testSecurityLoggingDelegate()370     public void testSecurityLoggingDelegate() throws Exception {
371         installAppAsUser(DELEGATE_APP_APK, mDeviceOwnerUserId);
372         try {
373             // Test that the delegate cannot access the logs already
374             runDeviceTestsAsUser(DELEGATE_APP_PKG, ".SecurityLoggingDelegateTest",
375                     "testCannotAccessApis", mDeviceOwnerUserId);
376 
377             // Set security logging delegate
378             executeDeviceTestMethodOnDeviceOwnerUser(".SecurityLoggingTest",
379                     "testSetDelegateScope_delegationSecurityLogging");
380 
381             runSecurityLoggingTests(DELEGATE_APP_PKG, ".SecurityLoggingDelegateTest");
382         } finally {
383             // Remove security logging delegate
384             executeDeviceTestMethodOnDeviceOwnerUser(".SecurityLoggingTest",
385                     "testSetDelegateScope_noDelegation");
386         }
387     }
388 
389     /**
390      * Test for {@link DevicePolicyManager.setStorageEncryption} and
391      * {@link DevicePolicyManager.getStorageEncryption}.
392      *
393      * <p>This test needs to run as as the device owner user ID since
394      * {@link DevicePolicyManager#setStorageEncryption(ComponentName, boolean)}
395      * is only allowed for system user.
396      */
397     @Override
398     @Test
testSetStorageEncryption()399     public void testSetStorageEncryption() throws Exception {
400         Map<String, String> params =
401                 ImmutableMap.of(IS_SYSTEM_USER_PARAM, String.valueOf(/* isSystemUser= */ true));
402         runDeviceTestsAsUser(
403                 DEVICE_ADMIN_PKG, STORAGE_ENCRYPTION_TEST_CLASS, null, mDeviceOwnerUserId, params);
404     }
405 
runSecurityLoggingTests(String packageName, String testClassName)406     private void runSecurityLoggingTests(String packageName, String testClassName)
407             throws Exception {
408         int userId = mDeviceOwnerUserId;
409         try {
410             // Turn logging on.
411             runDeviceTestsAsUser(packageName, testClassName, "testEnablingSecurityLogging", userId);
412             // Reboot to ensure ro.organization_owned is set to true in logd and logging is on.
413             rebootAndWaitUntilReady();
414             waitForUserUnlock(userId);
415 
416             // Generate various types of events on device side and check that they are logged.
417             runDeviceTestsAsUser(packageName, testClassName, "testGenerateLogs", userId);
418             runDeviceTestsAsUser(packageName, testClassName, "testVerifyGeneratedLogs", userId);
419 
420             // Immediately attempting to fetch events again should fail.
421             runDeviceTestsAsUser(packageName, testClassName,
422                     "testSecurityLoggingRetrievalRateLimited", userId);
423         } finally {
424             // Turn logging off.
425             runDeviceTestsAsUser(packageName, testClassName,
426                     "testDisablingSecurityLogging", userId);
427         }
428     }
429 
430     @Test
testLocationPermissionGrantNotifies()431     public void testLocationPermissionGrantNotifies() throws Exception {
432         installAppPermissionAppAsUser();
433         configureNotificationListener();
434         executeDeviceTestMethod(".PermissionsTest",
435                 "testPermissionGrantStateGranted_userNotifiedOfLocationPermission");
436     }
437 
438     @Override
439     @Test
testAdminControlOverSensorPermissionGrantsDefault()440     public void testAdminControlOverSensorPermissionGrantsDefault() throws Exception {
441         // In Device Owner mode, by default, admin should be able to grant sensors-related
442         // permissions.
443         executeDeviceTestMethod(".SensorPermissionGrantTest",
444                 "testAdminCanGrantSensorsPermissions");
445     }
446 
447     @Override
448     @Test
testGrantOfSensorsRelatedPermissions()449     public void testGrantOfSensorsRelatedPermissions() throws Exception {
450         // Skip for now, re-enable when the code path sets DO as able to grant permissions.
451     }
452 
453     @Override
454     @Test
testSensorsRelatedPermissionsNotGrantedViaPolicy()455     public void testSensorsRelatedPermissionsNotGrantedViaPolicy() throws Exception {
456         // Skip for now, re-enable when the code path sets DO as able to grant permissions.
457     }
458 
459     @Override
460     @Test
testStateOfSensorsRelatedPermissionsCannotBeRead()461     public void testStateOfSensorsRelatedPermissionsCannotBeRead() throws Exception {
462         // Skip because in DO mode the admin can read permission state.
463     }
464 
465     //TODO(b/180413140) Investigate why the test fails on DO mode.
466     @Override
467     @Test
testPermissionPrompts()468     public void testPermissionPrompts() throws Exception {
469     }
470 
471     @Override
472     @Test
473     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't launch activities")
testSuspendPackage()474     public void testSuspendPackage() throws Exception {
475         super.testSuspendPackage();
476     }
477 
478     @Override
479     @Test
480     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't launch activities")
testSuspendPackageWithPackageManager()481     public void testSuspendPackageWithPackageManager() throws Exception {
482         super.testSuspendPackageWithPackageManager();
483     }
484 
485     @Override
486     @Test
487     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't have credentials")
testGetPasswordExpiration()488     public void testGetPasswordExpiration() throws Exception {
489         super.testGetPasswordExpiration();
490     }
491 
492     @Override
493     @Test
494     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't have credentials")
testPasswordExpiration()495     public void testPasswordExpiration() throws Exception {
496         super.testPasswordExpiration();
497     }
498 
499     @Override
500     @Test
501     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't have credentials")
testResetPasswordWithToken()502     public void testResetPasswordWithToken() throws Exception {
503         super.testResetPasswordWithToken();
504     }
505 
506     @Override
507     @Test
508     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't have credentials")
testResetPasswordDeprecated()509     public void testResetPasswordDeprecated() throws Exception {
510         super.testResetPasswordDeprecated();
511     }
512 
513     @Override
514     @Test
515     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't launch activities")
testCreateAdminSupportIntent()516     public void testCreateAdminSupportIntent() throws Exception {
517         super.testCreateAdminSupportIntent();
518     }
519 
520     @Override
521     @Test
522     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't launch activities")
testPersistentIntentResolving()523     public void testPersistentIntentResolving() throws Exception {
524         super.testPersistentIntentResolving();
525     }
526 
527     @Override
528     @Test
529     @IgnoreOnHeadlessSystemUserMode(reason = "Headless system user doesn't launch activities")
testDisallowAutofill_allowed()530     public void testDisallowAutofill_allowed() throws Exception {
531         super.testDisallowAutofill_allowed();
532     }
533 
534     @Override
testApplicationHidden()535     public void testApplicationHidden() throws Exception {
536         if (isHeadlessSystemUserMode()) {
537             // Must run on user 0 because the test has a broadcast receiver that listen to packages
538             // added / removed intents
539             mUserId = mDeviceOwnerUserId;
540             CLog.d("testApplicationHidden(): setting mUserId as %d before running it", mUserId);
541         }
542         super.testApplicationHidden();
543     }
544 
545     @Override
installDelegateApp()546     protected void installDelegateApp() throws Exception {
547         // TODO(b/176993670): must call installDeviceOwnerApp() - even though it's not one - so
548         // the permissions required to use DpmWrapper are set on headless system user mode
549         installDeviceOwnerApp(DELEGATE_APP_APK);
550     }
551 
552     @Override
runDeviceTestsAsUser(String pkgName, String testClassName, String testName, int userId, Map<String, String> params)553     protected void runDeviceTestsAsUser(String pkgName, String testClassName, String testName,
554             int userId, Map<String, String> params) throws DeviceNotAvailableException {
555         Map<String, String> newParams = new HashMap(params);
556         newParams.putAll(getParamsForDeviceOwnerTest());
557         super.runDeviceTestsAsUser(
558                 pkgName, testClassName, testName, userId, newParams);
559     }
560 
561     @Override
executeDeviceTestMethod(String className, String testName, Map<String, String> params)562     protected void executeDeviceTestMethod(String className, String testName,
563             Map<String, String> params) throws Exception {
564         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, testName, mUserId, params);
565     }
566 
executeDeviceTestMethodOnDeviceOwnerUser(String className, String testName)567     private void executeDeviceTestMethodOnDeviceOwnerUser(String className, String testName)
568             throws Exception {
569         executeDeviceTestMethod(className, testName, mDeviceOwnerUserId,
570                 /* params= */ new HashMap<>());
571     }
572 
configureNotificationListener()573     private void configureNotificationListener() throws DeviceNotAvailableException {
574         getDevice().executeShellCommand("cmd notification allow_listener "
575                 + "com.android.cts.deviceandprofileowner/.NotificationListener");
576     }
577 
generateTestSecurityLogs()578     private void generateTestSecurityLogs() throws Exception {
579         // Trigger security events of type TAG_ADB_SHELL_CMD.
580         for (int i = 0; i < SECURITY_EVENTS_BATCH_SIZE; i++) {
581             getDevice().executeShellCommand("echo just_testing_" + i);
582         }
583     }
584 
createSecondaryUserAsProfileOwner()585     private int createSecondaryUserAsProfileOwner() throws Exception {
586         final int userId = createUserAndWaitStart();
587         installAppAsUser(INTENT_RECEIVER_APK, userId);
588         installAppAsUser(DEVICE_ADMIN_APK, userId);
589         // For headless system user mode, PO is set on any secondary user created
590         if (!isHeadlessSystemUserMode()) {
591             setProfileOwnerOrFail(DEVICE_ADMIN_COMPONENT_FLATTENED, userId);
592         }
593         return userId;
594     }
595 
switchToUser(int userId)596     private void switchToUser(int userId) throws Exception {
597         switchUser(userId);
598         waitForBroadcastIdle();
599         wakeupAndDismissKeyguard();
600     }
601 
setUserAsAffiliatedUserToPrimary(int userId)602     private void setUserAsAffiliatedUserToPrimary(int userId) throws Exception {
603         // Setting the same affiliation ids on both users
604         runDeviceTestsAsUser(
605                 DEVICE_ADMIN_PKG, ".AffiliationTest", "testSetAffiliationId1", mPrimaryUserId);
606         runDeviceTestsAsUser(
607                 DEVICE_ADMIN_PKG, ".AffiliationTest", "testSetAffiliationId1", userId);
608     }
609 }
610