1 /*
2  * Copyright (C) 2019 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.DeviceAdminFeaturesCheckerRule.FEATURE_MANAGED_USERS;
20 import static com.android.cts.devicepolicy.DeviceAndProfileOwnerTest.DEVICE_ADMIN_COMPONENT_FLATTENED;
21 import static com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier.assertMetricsLogged;
22 
23 import static com.google.common.truth.Truth.assertThat;
24 
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27 
28 import android.platform.test.annotations.FlakyTest;
29 import android.platform.test.annotations.LargeTest;
30 import android.stats.devicepolicy.EventId;
31 
32 import com.android.cts.devicepolicy.DeviceAdminFeaturesCheckerRule.RequiresAdditionalFeatures;
33 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
34 import com.android.tradefed.device.DeviceNotAvailableException;
35 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
36 import com.android.tradefed.util.RunUtil;
37 
38 import org.junit.Ignore;
39 import org.junit.Rule;
40 import org.junit.Test;
41 
42 import java.util.concurrent.TimeUnit;
43 
44 /**
45  * Tests for organization-owned Profile Owner.
46  */
47 // We need managed users to be supported in order to create a profile of the user owner.
48 @RequiresAdditionalFeatures({FEATURE_MANAGED_USERS})
49 public final class OrgOwnedProfileOwnerTest extends BaseDevicePolicyTest {
50     private static final String DEVICE_ADMIN_PKG = DeviceAndProfileOwnerTest.DEVICE_ADMIN_PKG;
51     private static final String DEVICE_ADMIN_APK = DeviceAndProfileOwnerTest.DEVICE_ADMIN_APK;
52     private static final String CERT_INSTALLER_PKG = DeviceAndProfileOwnerTest.CERT_INSTALLER_PKG;
53     private static final String CERT_INSTALLER_APK = DeviceAndProfileOwnerTest.CERT_INSTALLER_APK;
54     private static final String DELEGATE_APP_PKG = DeviceAndProfileOwnerTest.DELEGATE_APP_PKG;
55     private static final String DELEGATE_APP_APK = DeviceAndProfileOwnerTest.DELEGATE_APP_APK;
56     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
57 
58     private static final String ADMIN_RECEIVER_TEST_CLASS =
59             DeviceAndProfileOwnerTest.ADMIN_RECEIVER_TEST_CLASS;
60     private static final String ACTION_WIPE_DATA =
61             "com.android.cts.deviceandprofileowner.WIPE_DATA";
62 
63     private static final String TEST_APP_APK = "CtsSimpleApp.apk";
64     private static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp";
65     private static final String TEST_IME_APK = "TestIme.apk";
66     private static final String TEST_IME_PKG = "com.android.cts.testime";
67     private static final String TEST_IME_COMPONENT = TEST_IME_PKG + "/.TestIme";
68     private static final String SIMPLE_SMS_APP_PKG = "android.telephony.cts.sms.simplesmsapp";
69     private static final String SIMPLE_SMS_APP_APK = "SimpleSmsApp.apk";
70     public static final String SUSPENSION_CHECKER_CLASS =
71             "com.android.cts.suspensionchecker.ActivityLaunchTest";
72 
73     private static final String USER_IS_NOT_STARTED = "User is not started";
74     private static final long USER_STOP_TIMEOUT_SEC = 60;
75 
76     protected int mUserId;
77     private static final String DISALLOW_CONFIG_LOCATION = "no_config_location";
78     private static final String CALLED_FROM_PARENT = "calledFromParent";
79 
80     @Rule
81     public DeviceJUnit4ClassRunner.TestLogData mLogger = new DeviceJUnit4ClassRunner.TestLogData();
82 
83     @Override
setUp()84     public void setUp() throws Exception {
85         super.setUp();
86 
87         removeTestUsers();
88         createManagedProfile();
89     }
90 
createManagedProfile()91     private void createManagedProfile() throws Exception {
92         mUserId = createManagedProfile(mPrimaryUserId);
93         switchUser(mPrimaryUserId);
94         startUserAndWait(mUserId);
95 
96         installAppAsUser(DEVICE_ADMIN_APK, mUserId);
97         setProfileOwnerOrFail(DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mUserId);
98         startUserAndWait(mUserId);
99         restrictManagedProfileRemoval();
100     }
101 
102     @Override
tearDown()103     public void tearDown() throws Exception {
104         // Managed profile and other test users will be removed by BaseDevicePolicyTest.tearDown()
105         super.tearDown();
106     }
107 
restrictManagedProfileRemoval()108     private void restrictManagedProfileRemoval() throws DeviceNotAvailableException {
109             getDevice().executeShellCommand(
110                     String.format("dpm mark-profile-owner-on-organization-owned-device --user %d '%s'",
111                             mUserId, DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS));
112     }
113 
114     @Test
testCanRelinquishControlOverDevice()115     public void testCanRelinquishControlOverDevice() throws Exception {
116         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".LockScreenInfoTest", "testSetAndGetLockInfo",
117                 mUserId);
118 
119         removeOrgOwnedProfile();
120         assertHasNoUser(mUserId);
121 
122         try {
123             installAppAsUser(DEVICE_ADMIN_APK, /* userId= */ 0);
124             assertTrue(setDeviceOwner(DEVICE_ADMIN_COMPONENT_FLATTENED,
125                     /* userId= */ 0, /*expectFailure*/false));
126             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".LockScreenInfoTest", "testLockInfoIsNull",
127                     /* userId= */ 0);
128         } finally {
129             removeAdmin(DEVICE_ADMIN_COMPONENT_FLATTENED, /* userId= */ 0);
130             getDevice().uninstallPackage(DEVICE_ADMIN_PKG);
131         }
132     }
133 
134     @Test
testLockScreenInfo()135     public void testLockScreenInfo() throws Exception {
136         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".LockScreenInfoTest", mUserId);
137     }
138 
139     @Test
testProfileOwnerCanGetDeviceIdentifiers()140     public void testProfileOwnerCanGetDeviceIdentifiers() throws Exception {
141         // The Profile Owner should have access to all device identifiers.
142         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DeviceIdentifiersTest",
143                 "testProfileOwnerCanGetDeviceIdentifiersWithPermission", mUserId);
144     }
145 
146     @Test
testDevicePolicyManagerParentSupport()147     public void testDevicePolicyManagerParentSupport() throws Exception {
148         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".OrgOwnedProfileOwnerParentTest", mUserId);
149     }
150 
151     @Test
testUserRestrictionSetOnParentLogged()152     public void testUserRestrictionSetOnParentLogged() throws Exception {
153         assertMetricsLogged(getDevice(), () -> {
154             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DevicePolicyLoggingParentTest",
155                     "testUserRestrictionLogged", mUserId);
156                 }, new DevicePolicyEventWrapper.Builder(EventId.ADD_USER_RESTRICTION_VALUE)
157                         .setAdminPackageName(DEVICE_ADMIN_PKG)
158                         .setStrings(DISALLOW_CONFIG_LOCATION, CALLED_FROM_PARENT)
159                         .build(),
160                 new DevicePolicyEventWrapper.Builder(EventId.REMOVE_USER_RESTRICTION_VALUE)
161                         .setAdminPackageName(DEVICE_ADMIN_PKG)
162                         .setStrings(DISALLOW_CONFIG_LOCATION, CALLED_FROM_PARENT)
163                         .build());
164     }
165 
166     @Test
testUserRestrictionsSetOnParentAreNotPersisted()167     public void testUserRestrictionsSetOnParentAreNotPersisted() throws Exception {
168         assumeCanCreateAdditionalUsers(1);
169 
170         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
171         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
172                 "testAddUserRestrictionDisallowConfigDateTime_onParent", mUserId);
173         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
174                 "testHasUserRestrictionDisallowConfigDateTime", mPrimaryUserId);
175         removeOrgOwnedProfile();
176         assertHasNoUser(mUserId);
177 
178         // User restrictions are not persist after organization-owned profile owner is removed
179         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
180                 "testUserRestrictionDisallowConfigDateTimeIsNotPersisted", mPrimaryUserId);
181     }
182 
183     @Test
testPerProfileUserRestrictionOnParent()184     public void testPerProfileUserRestrictionOnParent() throws Exception {
185         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
186                 "testPerProfileUserRestriction_onParent", mUserId);
187     }
188 
189     @Test
testPerDeviceUserRestrictionOnParent()190     public void testPerDeviceUserRestrictionOnParent() throws Exception {
191         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
192                 "testPerDeviceUserRestriction_onParent", mUserId);
193     }
194 
195     @Test
testCameraDisabledOnParentIsEnforced()196     public void testCameraDisabledOnParentIsEnforced() throws Exception {
197         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
198         try {
199             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
200                     "testAddUserRestrictionCameraDisabled_onParent", mUserId);
201             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
202                     "testCannotOpenCamera", mPrimaryUserId);
203         } finally {
204             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
205                     "testRemoveUserRestrictionCameraEnabled_onParent", mUserId);
206             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
207                     "testCanOpenCamera", mPrimaryUserId);
208         }
209     }
210 
211     @Test
testCameraDisabledOnParentLogged()212     public void testCameraDisabledOnParentLogged() throws Exception {
213         assertMetricsLogged(getDevice(), () -> {
214                     runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DevicePolicyLoggingParentTest",
215                             "testCameraDisabledLogged", mUserId);
216                 }, new DevicePolicyEventWrapper.Builder(EventId.SET_CAMERA_DISABLED_VALUE)
217                         .setAdminPackageName(DEVICE_ADMIN_PKG)
218                         .setBoolean(true)
219                         .setStrings(CALLED_FROM_PARENT)
220                         .build(),
221                 new DevicePolicyEventWrapper.Builder(EventId.SET_CAMERA_DISABLED_VALUE)
222                         .setAdminPackageName(DEVICE_ADMIN_PKG)
223                         .setBoolean(false)
224                         .setStrings(CALLED_FROM_PARENT)
225                         .build());
226     }
227 
228     @Test
testSecurityLogging()229     public void testSecurityLogging() throws Exception {
230         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
231         testSecurityLoggingOnWorkProfile(DEVICE_ADMIN_PKG, ".SecurityLoggingTest");
232     }
233 
234     @Test
testSecurityLoggingDelegate()235     public void testSecurityLoggingDelegate() throws Exception {
236         installAppAsUser(DELEGATE_APP_APK, mUserId);
237         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
238         try {
239             runDeviceTestsAsUser(DELEGATE_APP_PKG, ".SecurityLoggingDelegateTest",
240                     "testCannotAccessApis", mUserId);
241             // Set security logging delegate
242             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".SecurityLoggingTest",
243                     "testSetDelegateScope_delegationSecurityLogging", mUserId);
244 
245             testSecurityLoggingOnWorkProfile(DELEGATE_APP_PKG,
246                     ".SecurityLoggingDelegateTest");
247         } finally {
248             // Remove security logging delegate
249             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".SecurityLoggingTest",
250                     "testSetDelegateScope_noDelegation", mUserId);
251         }
252     }
253 
testSecurityLoggingOnWorkProfile(String packageName, String testClassName)254     private void testSecurityLoggingOnWorkProfile(String packageName, String testClassName)
255             throws Exception {
256         // Backup stay awake setting because testGenerateLogs() will turn it off.
257         final String stayAwake = getDevice().getSetting("global", "stay_on_while_plugged_in");
258         try {
259             // Turn logging on.
260             runDeviceTestsAsUser(packageName, testClassName,
261                     "testEnablingSecurityLogging", mUserId);
262 
263             // Ensure user is initialized before rebooting, otherwise it won't start.
264             waitForUserInitialized(mUserId);
265             // Wait until idle so that the flag is persisted to disk.
266             waitForBroadcastIdle();
267             // Reboot to ensure ro.organization_owned is set to true in logd and logging is on.
268             rebootAndWaitUntilReady();
269             waitForUserUnlock(mUserId);
270 
271             // Generate various types of events on device side and check that they are logged.
272             runDeviceTestsAsUser(packageName, testClassName, "testGenerateLogs", mUserId);
273             getDevice().executeShellCommand("whoami"); // Generate adb command securty event
274             runDeviceTestsAsUser(packageName, testClassName, "testVerifyGeneratedLogs", mUserId);
275 
276             // Immediately attempting to fetch events again should fail.
277             runDeviceTestsAsUser(packageName, testClassName,
278                     "testSecurityLoggingRetrievalRateLimited", mUserId);
279         } finally {
280             // Turn logging off.
281             runDeviceTestsAsUser(packageName, testClassName,
282                     "testDisablingSecurityLogging", mUserId);
283             // Restore stay awake setting.
284             if (stayAwake != null) {
285                 getDevice().setSetting("global", "stay_on_while_plugged_in", stayAwake);
286             }
287         }
288     }
289 
waitForUserInitialized(int userId)290     private void waitForUserInitialized(int userId) throws Exception {
291         final long start = System.nanoTime();
292         final long deadline = start + TimeUnit.MINUTES.toNanos(5);
293         while ((getUserFlags(userId) & FLAG_INITIALIZED) == 0) {
294             if (System.nanoTime() > deadline) {
295                 fail("Timed out waiting for user to become initialized");
296             }
297             RunUtil.getDefault().sleep(100);
298         }
299     }
300 
301     @LargeTest
302     @Test
303     @Ignore("b/145932189")
testSystemUpdatePolicy()304     public void testSystemUpdatePolicy() throws Exception {
305         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".systemupdate.SystemUpdatePolicyTest", mUserId);
306     }
307 
308     @Test
testInstallUpdate()309     public void testInstallUpdate() throws Exception {
310         pushUpdateFileToDevice("notZip.zi");
311         pushUpdateFileToDevice("empty.zip");
312         pushUpdateFileToDevice("wrongPayload.zip");
313         pushUpdateFileToDevice("wrongHash.zip");
314         pushUpdateFileToDevice("wrongSize.zip");
315         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".systemupdate.InstallUpdateTest", mUserId);
316     }
317 
318     @Test
testIsDeviceOrganizationOwnedWithManagedProfile()319     public void testIsDeviceOrganizationOwnedWithManagedProfile() throws Exception {
320         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DeviceOwnershipTest",
321                 "testCallingIsOrganizationOwnedWithManagedProfileExpectingTrue",
322                 mUserId);
323 
324         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
325         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DeviceOwnershipTest",
326                 "testCallingIsOrganizationOwnedWithManagedProfileExpectingTrue",
327                 mPrimaryUserId);
328     }
329 
330     @Test
testCommonCriteriaMode()331     public void testCommonCriteriaMode() throws Exception {
332         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".CommonCriteriaModeTest", mUserId);
333     }
334 
removeOrgOwnedProfile()335     private void removeOrgOwnedProfile() throws Exception {
336         sendWipeProfileBroadcast(mUserId);
337         waitUntilUserRemoved(mUserId);
338     }
339 
sendWipeProfileBroadcast(int userId)340     private void sendWipeProfileBroadcast(int userId) throws Exception {
341         final String cmd = "am broadcast --receiver-foreground --user " + userId
342                 + " -a " + ACTION_WIPE_DATA
343                 + " com.android.cts.deviceandprofileowner/.WipeDataReceiver";
344         getDevice().executeShellCommand(cmd);
345     }
346 
setPersonalAppsSuspended(boolean suspended)347     private void setPersonalAppsSuspended(boolean suspended) throws DeviceNotAvailableException {
348         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
349                 suspended ? "testSuspendPersonalApps" : "testUnsuspendPersonalApps", mUserId);
350     }
351 
addSmsRole(String app, int userId)352     private void addSmsRole(String app, int userId) throws Exception {
353         executeShellCommand(String.format(
354                 "cmd role add-role-holder --user %d android.app.role.SMS %s", userId, app));
355     }
356 
removeSmsRole(String app, int userId)357     private void removeSmsRole(String app, int userId) throws Exception {
358         executeShellCommand(String.format(
359                 "cmd role remove-role-holder --user %d android.app.role.SMS %s", userId, app));
360     }
361 
362     @Test
testPersonalAppsSuspensionIme()363     public void testPersonalAppsSuspensionIme() throws Exception {
364         installAppAsUser(TEST_IME_APK, mPrimaryUserId);
365         setupIme(TEST_IME_COMPONENT, mPrimaryUserId);
366         setPersonalAppsSuspended(true);
367         // Active IME should not be suspended.
368         assertCanStartPersonalApp(TEST_IME_PKG, true);
369         setPersonalAppsSuspended(false);
370     }
371 
372     @Test
testPermittedInputMethods()373     public void testPermittedInputMethods() throws Exception {
374         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".InputMethodsTest", mUserId);
375     }
376 
377     @Test
testPermittedInputMethodsLogged()378     public void testPermittedInputMethodsLogged() throws Exception {
379         assertMetricsLogged(getDevice(), () ->
380                         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".InputMethodsTest",
381                                 "testPermittedInputMethodsOnParent", mUserId),
382                 new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
383                         .setAdminPackageName(DEVICE_ADMIN_PKG)
384                         .setStrings(CALLED_FROM_PARENT, new String[0])
385                         .build(),
386                 new DevicePolicyEventWrapper.Builder(EventId.SET_PERMITTED_INPUT_METHODS_VALUE)
387                         .setAdminPackageName(DEVICE_ADMIN_PKG)
388                         .setStrings(CALLED_FROM_PARENT, new String[0])
389                         .build());
390     }
391 
setupIme(String imeComponent, int userId)392     private void setupIme(String imeComponent, int userId) throws Exception {
393         // Wait until IMS service is registered by the system.
394         waitForOutput("Failed waiting for IME to become available",
395                 String.format("ime list --user %d -s -a", userId),
396                 s -> s.contains(imeComponent), 100 /* seconds */);
397 
398         executeShellCommand("ime enable " + imeComponent);
399         executeShellCommand("ime set " + imeComponent);
400     }
401 
assertCanStartPersonalApp(String packageName, boolean canStart)402     private void assertCanStartPersonalApp(String packageName, boolean canStart)
403             throws DeviceNotAvailableException {
404         runDeviceTestsAsUser(packageName, "com.android.cts.suspensionchecker.ActivityLaunchTest",
405                 canStart ? "testCanStartActivity" : "testCannotStartActivity", mPrimaryUserId);
406     }
407 
assertHasNoUser(int userId)408     private void assertHasNoUser(int userId) throws DeviceNotAvailableException {
409         int numWaits = 0;
410         final int MAX_NUM_WAITS = 15;
411         while (listUsers().contains(userId) && (numWaits < MAX_NUM_WAITS)) {
412             RunUtil.getDefault().sleep(1000);
413             numWaits += 1;
414         }
415 
416         assertThat(listUsers()).doesNotContain(userId);
417     }
418 
setPoAsUser(int userId)419     private void setPoAsUser(int userId) throws Exception {
420         installAppAsUser(DEVICE_ADMIN_APK, true, true, userId);
421         assertTrue("Failed to set profile owner",
422                 setProfileOwner(DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS,
423                         userId, /* expectFailure */ false));
424     }
425 
426     @Test
testSetPersonalAppsSuspendedLogged()427     public void testSetPersonalAppsSuspendedLogged() throws Exception {
428         assertMetricsLogged(getDevice(), () -> {
429                     runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DevicePolicyLoggingTest",
430                             "testSetPersonalAppsSuspendedLogged", mUserId);
431                 }, new DevicePolicyEventWrapper.Builder(EventId.SET_PERSONAL_APPS_SUSPENDED_VALUE)
432                         .setAdminPackageName(DEVICE_ADMIN_PKG)
433                         .setBoolean(true)
434                         .build(),
435                 new DevicePolicyEventWrapper.Builder(EventId.SET_PERSONAL_APPS_SUSPENDED_VALUE)
436                         .setAdminPackageName(DEVICE_ADMIN_PKG)
437                         .setBoolean(false)
438                         .build());
439     }
440 
441     @Test
testSetManagedProfileMaximumTimeOffLogged()442     public void testSetManagedProfileMaximumTimeOffLogged() throws Exception {
443         assertMetricsLogged(getDevice(), () -> {
444                     runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
445                             "testSetManagedProfileMaximumTimeOff", mUserId);
446                 }, new DevicePolicyEventWrapper.Builder(
447                         EventId.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF_VALUE)
448                         .setAdminPackageName(DEVICE_ADMIN_PKG)
449                         .setTimePeriod(123456789)
450                         .build(),
451                 new DevicePolicyEventWrapper.Builder(
452                         EventId.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF_VALUE)
453                         .setAdminPackageName(DEVICE_ADMIN_PKG)
454                         .setTimePeriod(0)
455                         .build());
456     }
457 
458     @Test
testWorkProfileMaximumTimeOff_complianceRequiredBroadcastDefault()459     public void testWorkProfileMaximumTimeOff_complianceRequiredBroadcastDefault()
460             throws Exception {
461         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
462         // Very long timeout, won't be triggered
463         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
464                 "testSetManagedProfileMaximumTimeOff1Year", mUserId);
465 
466         try {
467             toggleQuietMode(true);
468             waitForBroadcastIdle();
469             toggleQuietMode(false);
470             // Ensure the DPC has handled the broadcast
471             waitForBroadcastIdle();
472             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
473                     "testComplianceAcknowledgementRequiredReceived", mUserId);
474 
475             // Ensure that the default onComplianceAcknowledgementRequired acknowledged compliance.
476             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
477                     "testComplianceAcknowledgementNotRequired", mUserId);
478 
479         } finally {
480             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
481                     "testClearComplianceSharedPreference", mUserId);
482         }
483     }
484 
485     @Test
testWorkProfileMaximumTimeOff_complianceRequiredBroadcastOverride()486     public void testWorkProfileMaximumTimeOff_complianceRequiredBroadcastOverride()
487             throws Exception {
488         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
489         // Very long timeout, won't be triggered
490         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
491                 "testSetManagedProfileMaximumTimeOff1Year", mUserId);
492         // Set shared preference that instructs the receiver to NOT call default implementation.
493         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
494                 "testSetOverrideOnComplianceAcknowledgementRequired", mUserId);
495 
496         try {
497             toggleQuietMode(true);
498             waitForBroadcastIdle();
499             toggleQuietMode(false);
500             // Ensure the DPC has handled the broadcast
501             waitForBroadcastIdle();
502             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
503                     "testComplianceAcknowledgementRequiredReceived", mUserId);
504 
505             // Ensure compliance wasn't acknowledged automatically, acknowledge explicitly.
506             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
507                     "testAcknowledgeCompliance", mUserId);
508         } finally {
509             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
510                     "testClearComplianceSharedPreference", mUserId);
511         }
512     }
513 
514     @Test
testDelegatedCertInstallerDeviceIdAttestation()515     public void testDelegatedCertInstallerDeviceIdAttestation() throws Exception {
516         installAppAsUser(CERT_INSTALLER_APK, mUserId);
517 
518         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DelegatedCertInstallerHelper",
519                 "testManualSetCertInstallerDelegate", mUserId);
520 
521         runDeviceTestsAsUser(CERT_INSTALLER_PKG, ".DelegatedDeviceIdAttestationTest",
522                 "testGenerateKeyPairWithDeviceIdAttestationExpectingSuccess", mUserId);
523     }
524 
525     @Test
testDeviceIdAttestationForProfileOwner()526     public void testDeviceIdAttestationForProfileOwner() throws Exception {
527         // Test that Device ID attestation works for org-owned profile owner.
528         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".DeviceIdAttestationTest",
529                 "testSucceedsWithProfileOwnerIdsGrant", mUserId);
530 
531     }
532 
533     @Test
testNetworkLogging()534     public void testNetworkLogging() throws Exception {
535         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
536         testNetworkLoggingOnWorkProfile(DEVICE_ADMIN_PKG, ".NetworkLoggingTest");
537     }
538 
539     @Test
testNetworkLoggingDelegate()540     public void testNetworkLoggingDelegate() throws Exception {
541         installAppAsUser(DELEGATE_APP_APK, mUserId);
542         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
543         try {
544             runDeviceTestsAsUser(DELEGATE_APP_PKG, ".WorkProfileNetworkLoggingDelegateTest",
545                     "testCannotAccessApis", mUserId);
546             // Set network logging delegate
547             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".NetworkLoggingTest",
548                     "testSetDelegateScope_delegationNetworkLogging", mUserId);
549 
550             testNetworkLoggingOnWorkProfile(DELEGATE_APP_PKG,
551                     ".WorkProfileNetworkLoggingDelegateTest");
552         } finally {
553             // Remove network logging delegate
554             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".NetworkLoggingTest",
555                     "testSetDelegateScope_noDelegation", mUserId);
556         }
557     }
558 
testNetworkLoggingOnWorkProfile(String packageName, String testClassName)559     private void testNetworkLoggingOnWorkProfile(String packageName, String testClassName)
560             throws Exception {
561         try {
562             // Turn network logging on.
563             runDeviceTestsAsUser(packageName, testClassName,
564                     "testSetNetworkLogsEnabled_true", mUserId);
565 
566             // Connect to websites from work profile, should be logged.
567             runDeviceTestsAsUser(packageName, testClassName,
568                     "testConnectToWebsites_shouldBeLogged", mUserId);
569             // Connect to websites from personal profile, should not be logged.
570             runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".NetworkLoggingTest",
571                     "testConnectToWebsites_shouldNotBeLogged", mPrimaryUserId);
572 
573             // Verify all work profile network logs have been received.
574             runDeviceTestsAsUser(packageName, testClassName,
575                     "testRetrieveNetworkLogs_forceNetworkLogs_receiveNetworkLogs", mUserId);
576         } finally {
577             // Turn network logging off.
578             runDeviceTestsAsUser(packageName, testClassName,
579                     "testSetNetworkLogsEnabled_false", mUserId);
580         }
581     }
582 
583     @Test
testNetworkLoggingLogged()584     public void testNetworkLoggingLogged() throws Exception {
585         installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
586         assertMetricsLogged(getDevice(), () -> {
587             testNetworkLoggingOnWorkProfile(DEVICE_ADMIN_PKG, ".NetworkLoggingTest");
588         }, new DevicePolicyEventWrapper.Builder(EventId.SET_NETWORK_LOGGING_ENABLED_VALUE)
589                 .setAdminPackageName(DEVICE_ADMIN_PKG)
590                 .setBoolean(false)
591                 .setInt(1)
592                 .setStrings(LOG_TAG_PROFILE_OWNER)
593                 .build(),
594            new DevicePolicyEventWrapper.Builder(EventId.RETRIEVE_NETWORK_LOGS_VALUE)
595                 .setAdminPackageName(DEVICE_ADMIN_PKG)
596                 .setBoolean(false)
597                 .setStrings(LOG_TAG_PROFILE_OWNER)
598                 .build(),
599            new DevicePolicyEventWrapper.Builder(EventId.SET_NETWORK_LOGGING_ENABLED_VALUE)
600                 .setAdminPackageName(DEVICE_ADMIN_PKG)
601                 .setBoolean(false)
602                 .setInt(0)
603                 .setStrings(LOG_TAG_PROFILE_OWNER)
604                 .build());
605     }
606 
toggleQuietMode(boolean quietModeEnable)607     private void toggleQuietMode(boolean quietModeEnable) throws Exception {
608         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".PersonalAppsSuspensionTest",
609                 quietModeEnable ? "testEnableQuietMode" : "testDisableQuietMode", mPrimaryUserId);
610 
611         boolean keepProfilesRunning = executeShellCommand("dumpsys device_policy")
612                 .contains("Keep profiles running: true");
613         if (!keepProfilesRunning) {
614             if (quietModeEnable) {
615                 waitForUserStopped(mUserId);
616             } else {
617                 waitForUserUnlock(mUserId);
618             }
619         }
620     }
621 
setAndStartLauncher(String component)622     private void setAndStartLauncher(String component) throws Exception {
623         String output = getDevice().executeShellCommand(String.format(
624                 "cmd package set-home-activity --user %d %s", mPrimaryUserId, component));
625         assertTrue("failed to set home activity", output.contains("Success"));
626         executeShellCommand("am start -W -n " + component);
627     }
628 
waitForUserStopped(int userId)629     private void waitForUserStopped(int userId) throws Exception {
630         waitForOutput("User is not unlocked.",
631                 String.format("am get-started-user-state %d", userId),
632                 s -> s.startsWith(USER_IS_NOT_STARTED), USER_STOP_TIMEOUT_SEC);
633     }
634 }
635