1 /*
2  * Copyright (C) 2016 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 package com.android.managedprovisioning.preprovisioning;
17 
18 import static android.app.Activity.RESULT_CANCELED;
19 import static android.app.Activity.RESULT_OK;
20 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE;
21 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE;
22 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE;
23 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE;
24 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE;
25 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES;
26 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMERS;
27 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_CONTENT;
28 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_HEADER;
29 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_IMEI;
30 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION;
31 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED;
32 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_LOCALE;
33 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_LOCAL_TIME;
34 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_MODE;
35 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT;
36 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_SERIAL_NUMBER;
37 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_SKIP_ENCRYPTION;
38 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE;
39 import static android.app.admin.DevicePolicyManager.EXTRA_ROLE_HOLDER_STATE;
40 import static android.app.admin.DevicePolicyManager.EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE;
41 import static android.app.admin.DevicePolicyManager.FLAG_SUPPORTED_MODES_DEVICE_OWNER;
42 import static android.app.admin.DevicePolicyManager.FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED;
43 import static android.app.admin.DevicePolicyManager.FLAG_SUPPORTED_MODES_PERSONALLY_OWNED;
44 import static android.app.admin.DevicePolicyManager.PROVISIONING_MODE_FULLY_MANAGED_DEVICE;
45 import static android.app.admin.DevicePolicyManager.PROVISIONING_MODE_MANAGED_PROFILE;
46 import static android.app.admin.DevicePolicyManager.PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE;
47 import static android.app.admin.DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED;
48 import static android.app.admin.DevicePolicyManager.STATUS_OK;
49 
50 import static com.android.managedprovisioning.TestUtils.assertBundlesEqual;
51 import static com.android.managedprovisioning.common.Globals.ACTION_RESUME_PROVISIONING;
52 import static com.android.managedprovisioning.model.ProvisioningParams.DEFAULT_LOCAL_TIME;
53 
54 import static com.google.common.truth.Truth.assertThat;
55 
56 import static org.mockito.ArgumentMatchers.anyBoolean;
57 import static org.mockito.Mockito.any;
58 import static org.mockito.Mockito.anyInt;
59 import static org.mockito.Mockito.anyString;
60 import static org.mockito.Mockito.eq;
61 import static org.mockito.Mockito.mock;
62 import static org.mockito.Mockito.never;
63 import static org.mockito.Mockito.times;
64 import static org.mockito.Mockito.verify;
65 import static org.mockito.Mockito.verifyNoMoreInteractions;
66 import static org.mockito.Mockito.when;
67 import static org.mockito.Mockito.withSettings;
68 import static org.testng.Assert.assertThrows;
69 
70 import android.app.ActivityManager;
71 import android.app.KeyguardManager;
72 import android.app.admin.DevicePolicyManager;
73 import android.content.ComponentName;
74 import android.content.ContentInterface;
75 import android.content.ContentResolver;
76 import android.content.Context;
77 import android.content.Intent;
78 import android.content.pm.ApplicationInfo;
79 import android.content.pm.PackageInfo;
80 import android.content.pm.PackageManager;
81 import android.content.pm.ResolveInfo;
82 import android.content.res.Resources;
83 import android.graphics.drawable.VectorDrawable;
84 import android.net.NetworkCapabilities;
85 import android.net.Uri;
86 import android.os.Bundle;
87 import android.os.Handler;
88 import android.os.Looper;
89 import android.os.Parcelable;
90 import android.os.PersistableBundle;
91 import android.os.UserHandle;
92 import android.os.UserManager;
93 import android.service.persistentdata.PersistentDataBlockManager;
94 import android.telephony.TelephonyManager;
95 import android.text.TextUtils;
96 
97 import androidx.test.core.app.ApplicationProvider;
98 import androidx.test.filters.SmallTest;
99 import androidx.test.platform.app.InstrumentationRegistry;
100 
101 import com.android.managedprovisioning.R;
102 import com.android.managedprovisioning.analytics.TimeLogger;
103 import com.android.managedprovisioning.common.DeviceManagementRoleHolderHelper;
104 import com.android.managedprovisioning.common.DeviceManagementRoleHolderUpdaterHelper;
105 import com.android.managedprovisioning.common.FeatureFlagChecker;
106 import com.android.managedprovisioning.common.GetProvisioningModeUtils;
107 import com.android.managedprovisioning.common.IllegalProvisioningArgumentException;
108 import com.android.managedprovisioning.common.ManagedProvisioningSharedPreferences;
109 import com.android.managedprovisioning.common.PolicyComplianceUtils;
110 import com.android.managedprovisioning.common.RoleGranter;
111 import com.android.managedprovisioning.common.SettingsFacade;
112 import com.android.managedprovisioning.common.Utils;
113 import com.android.managedprovisioning.model.DisclaimersParam;
114 import com.android.managedprovisioning.model.PackageDownloadInfo;
115 import com.android.managedprovisioning.model.ProvisioningParams;
116 import com.android.managedprovisioning.model.WifiInfo;
117 import com.android.managedprovisioning.parser.MessageParser;
118 import com.android.managedprovisioning.preprovisioning.PreProvisioningActivityController.UiParams;
119 import com.android.managedprovisioning.util.LazyStringResource;
120 
121 import org.junit.Before;
122 import org.junit.Test;
123 import org.mockito.ArgumentCaptor;
124 import org.mockito.Mock;
125 import org.mockito.MockitoAnnotations;
126 
127 import java.util.ArrayList;
128 import java.util.List;
129 import java.util.Locale;
130 
131 @SmallTest
132 public class PreProvisioningActivityControllerTest {
133     private static final String TEST_MDM_PACKAGE = "com.test.mdm";
134     private static final String TEST_MDM_PACKAGE_LABEL = "Test MDM";
135     private static final CharSequence DEFAULT_DEVICE_NAME = "device";
136     private static final ComponentName TEST_MDM_COMPONENT_NAME = new ComponentName(TEST_MDM_PACKAGE,
137             "com.test.mdm.DeviceAdmin");
138     private static final String TEST_BOGUS_PACKAGE = "com.test.bogus";
139     private static final String TEST_WIFI_SSID = "\"TestNet\"";
140     private static final String MP_PACKAGE_NAME = "com.android.managedprovisioning";
141     private static final int TEST_USER_ID = 10;
142     private static final PackageDownloadInfo PACKAGE_DOWNLOAD_INFO =
143             PackageDownloadInfo.Builder.builder()
144                     .setCookieHeader("COOKIE_HEADER")
145                     .setLocation("LOCATION")
146                     .setMinVersion(1)
147                     .setPackageChecksum(new byte[] {1})
148                     .setSignatureChecksum(new byte[] {1})
149                     .build();
150     public static final ProvisioningParams DOWNLOAD_ROLE_HOLDER_PARAMS_WITH_ALLOW_OFFLINE =
151             ProvisioningParams.Builder.builder()
152                     .setProvisioningAction(ACTION_PROVISION_MANAGED_PROFILE)
153                     .setDeviceAdminComponentName(TEST_MDM_COMPONENT_NAME)
154                     .setRoleHolderDownloadInfo(PACKAGE_DOWNLOAD_INFO)
155                     .setAllowOffline(true)
156                     .build();
157     public static final ProvisioningParams DOWNLOAD_ROLE_HOLDER_PARAMS =
158             ProvisioningParams.Builder.builder()
159                     .setProvisioningAction(ACTION_PROVISION_MANAGED_PROFILE)
160                     .setDeviceAdminComponentName(TEST_MDM_COMPONENT_NAME)
161                     .setRoleHolderDownloadInfo(PACKAGE_DOWNLOAD_INFO)
162                     .build();
163     public static final ProvisioningParams ALLOW_OFFLINE_PARAMS =
164             ProvisioningParams.Builder.builder()
165                     .setProvisioningAction(ACTION_PROVISION_MANAGED_PROFILE)
166                     .setDeviceAdminComponentName(TEST_MDM_COMPONENT_NAME)
167                     .setAllowOffline(true)
168                     .build();
169     private static final String TEST_IMEI = "my imei";
170     private static final String DISCLAIMER_HEADER = "header1";
171     private static final Uri DISCLAIMER_CONTENT_URI =
172             Uri.parse("file:///test.example.uri/disclaimers.txt");
173     private static final DisclaimersParam.Disclaimer[] OTHER_DISCLAIMERS =
174             {new DisclaimersParam.Disclaimer("header2", "content2")};
175     private static final DisclaimersParam.Disclaimer[] DISCLAIMERS =
176             {new DisclaimersParam.Disclaimer(DISCLAIMER_HEADER, DISCLAIMER_CONTENT_URI.toString())};
177     private static final DisclaimersParam DISCLAIMERS_PARAM =
178             new DisclaimersParam.Builder().setDisclaimers(DISCLAIMERS).build();
179     private static final DisclaimersParam OTHER_DISCLAIMERS_PARAM =
180             new DisclaimersParam.Builder().setDisclaimers(OTHER_DISCLAIMERS).build();
181     private static final Parcelable[] DISCLAIMERS_EXTRA = createDisclaimersExtra();
182     private static final String LOCALE_EXTRA = "en_US";
183     private static final Locale LOCALE = Locale.US;
184     private static final Locale OTHER_LOCALE = Locale.CANADA;
185     private static final String INVALID_LOCALE_EXTRA = "INVALIDLOCALE";
186     private static final long LOCAL_TIME_EXTRA = 1234L;
187     private static final long OTHER_LOCAL_TIME = 4321L;
188     private static final String TIME_ZONE_EXTRA = "GMT";
189     private static final String OTHER_TIME_ZONE = "GMT+1";
190     private static final String TEST_ROLE_HOLDER_PACKAGE_NAME = "test.roleholder.package";
191     private static final String TEST_ROLE_HOLDER_UPDATER_PACKAGE_NAME =
192             "test.roleholderupdater.package";
193     private static final FeatureFlagChecker sFeatureFlagChecker = createFeatureFlagChecker();
194     private static final RoleGranter sRoleGranter =
195             (context, user, roleName, packageName, callback) -> callback.accept(true);
196     private static final DeviceManagementRoleHolderHelper
197             DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER =
198             new DeviceManagementRoleHolderHelper(
199                     TEST_ROLE_HOLDER_PACKAGE_NAME,
200                     /* packageInstallChecker= */ (packageName) -> true,
201                     /* resolveIntentChecker= */ (intent, packageManager) -> true,
202                     /* roleHolderStubChecker= */ (packageName, packageManager) -> false,
203                     sFeatureFlagChecker,
204                     sRoleGranter);
205     private static final DeviceManagementRoleHolderHelper
206             DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT =
207             new DeviceManagementRoleHolderHelper(
208                     TEST_ROLE_HOLDER_PACKAGE_NAME,
209                     /* packageInstallChecker= */ (packageName) -> false,
210                     /* resolveIntentChecker= */ (intent, packageManager) -> false,
211                     /* roleHolderStubChecker= */ (packageName, packageManager) -> false,
212                     sFeatureFlagChecker,
213                     sRoleGranter);
214     private static final String EMPTY_PACKAGE_NAME = "";
215     private static final DeviceManagementRoleHolderHelper
216             DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_CONFIGURED =
217             new DeviceManagementRoleHolderHelper(
218                     EMPTY_PACKAGE_NAME,
219                     /* packageInstallChecker= */ (packageManager) -> false,
220                     /* resolveIntentChecker= */ (intent, packageManager) -> false,
221                     /* roleHolderStubChecker= */ (packageName, packageManager) -> false,
222                     sFeatureFlagChecker,
223                     sRoleGranter);
224     private static final DeviceManagementRoleHolderUpdaterHelper
225             ROLE_HOLDER_UPDATER_HELPER =
226             new DeviceManagementRoleHolderUpdaterHelper(
227                     TEST_ROLE_HOLDER_UPDATER_PACKAGE_NAME,
228                     TEST_ROLE_HOLDER_PACKAGE_NAME,
229                     /* packageInstallChecker= */ (packageName) -> true,
230                     /* intentResolverChecker= */ (intent) -> true,
231                     sFeatureFlagChecker);
232     private static final DeviceManagementRoleHolderUpdaterHelper
233             ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_INSTALLED =
234             new DeviceManagementRoleHolderUpdaterHelper(
235                     TEST_ROLE_HOLDER_UPDATER_PACKAGE_NAME,
236                     TEST_ROLE_HOLDER_PACKAGE_NAME,
237                     /* packageInstallChecker= */ (packageName) -> false,
238                     /* intentResolverChecker= */ (intent) -> true,
239                     sFeatureFlagChecker);
240     private static final DeviceManagementRoleHolderUpdaterHelper
241             ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_DEFINED =
242             new DeviceManagementRoleHolderUpdaterHelper(
243                     /* roleHolderUpdaterPackageName= */ null,
244                     TEST_ROLE_HOLDER_PACKAGE_NAME,
245                     /* packageInstallChecker= */ (packageName) -> false,
246                     /* intentResolverChecker= */ (intent) -> true,
247                     sFeatureFlagChecker);
248     private static final PersistableBundle ROLE_HOLDER_STATE = createRoleHolderStateBundle();
249     private static final String TEST_CALLING_PACKAGE = "com.test.calling.package";
250     private static final Bundle ADDITIONAL_EXTRAS_DEFAULT = new Bundle();
251     private static final Bundle ADDITIONAL_EXTRAS_SUCCESSFUL_UPDATE =
252             createSuccessfulUpdateAdditionalExtras();
253     private static final Bundle GET_DEVICE_NAME_BUNDLE = new Bundle();
254     private final Context stringContext = ApplicationProvider.getApplicationContext();
255 
256     @Mock
257     private Context mContext;
258     @Mock
259     Resources mResources;
260     @Mock
261     private DevicePolicyManager mDevicePolicyManager;
262     @Mock
263     private UserManager mUserManager;
264     @Mock
265     private PackageManager mPackageManager;
266     @Mock
267     private ActivityManager mActivityManager;
268     @Mock
269     private KeyguardManager mKeyguardManager;
270     @Mock
271     private PersistentDataBlockManager mPdbManager;
272     @Mock
273     private PreProvisioningActivityController.Ui mUi;
274     @Mock
275     private MessageParser mMessageParser;
276     @Mock
277     private Utils mUtils;
278     @Mock
279     private SettingsFacade mSettingsFacade;
280     @Mock
281     private Intent mIntent;
282     @Mock
283     private EncryptionController mEncryptionController;
284     @Mock
285     private TimeLogger mTimeLogger;
286     @Mock
287     private ManagedProvisioningSharedPreferences mSharedPreferences;
288     @Mock
289     private TelephonyManager mTelephonyManager;
290     @Mock
291     private ContentInterface mContentInterface;
292 
293     private ProvisioningParams mParams;
294     private PreProvisioningViewModel mViewModel;
295     private ContentResolver mContentResolver;
296 
297     private PreProvisioningActivityController mController;
298     public static final PersistableBundle TEST_ADMIN_BUNDLE = new PersistableBundle();
299     private static boolean sDelegateProvisioningToRoleHolderEnabled;
300 
301     static {
302         TEST_ADMIN_BUNDLE.putInt("someKey", 123);
303     }
304     private Handler mHandler = new Handler(Looper.getMainLooper());
305 
306     @Before
setUp()307     public void setUp() throws PackageManager.NameNotFoundException {
308         MockitoAnnotations.initMocks(this);
309         mContentResolver = mock(ContentResolver.class,
310                 withSettings().useConstructor(mContext, mContentInterface));
311 
312         System.setProperty("dexmaker.dexcache",
313                 InstrumentationRegistry.getInstrumentation()
314                         .getTargetContext().getCacheDir().toString());
315 
316         when(mContext.getSystemServiceName(DevicePolicyManager.class))
317                 .thenReturn(Context.DEVICE_POLICY_SERVICE);
318         when(mContext.getSystemService(DevicePolicyManager.class))
319                 .thenReturn(mDevicePolicyManager);
320 
321         when(mContext.getSystemServiceName(UserManager.class))
322                 .thenReturn(Context.USER_SERVICE);
323         when(mContext.getSystemService(UserManager.class))
324                 .thenReturn(mUserManager);
325 
326         when(mContext.getPackageManager()).thenReturn(mPackageManager);
327         when(mContext.getSystemService(Context.ACTIVITY_SERVICE)).thenReturn(mActivityManager);
328         when(mContext.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(mKeyguardManager);
329         when(mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE))
330                 .thenReturn(mPdbManager);
331         when(mContext.getPackageName()).thenReturn(MP_PACKAGE_NAME);
332         when(mContext.getResources()).thenReturn(
333                 InstrumentationRegistry.getInstrumentation().getTargetContext().getResources());
334         when(mContext.getSystemServiceName(TelephonyManager.class))
335                 .thenReturn(Context.TELEPHONY_SERVICE);
336         when(mContext.getSystemService(TelephonyManager.class)).thenReturn(mTelephonyManager);
337         when(mTelephonyManager.getImei()).thenReturn(TEST_IMEI);
338 
339         when(mUserManager.getProcessUserId()).thenReturn(TEST_USER_ID);
340 
341         when(mUtils.getActiveNetworkCapabilities(any(Context.class)))
342                 .thenReturn(new NetworkCapabilities());
343         when(mUtils.isEncryptionRequired()).thenReturn(false);
344         when(mUtils.currentLauncherSupportsManagedProfiles(mContext)).thenReturn(true);
345         when(mUserManager.canAddMoreManagedProfiles(anyInt(), anyBoolean()))
346                 .thenReturn(true);
347 
348         when(mPackageManager.getApplicationIcon(anyString())).thenReturn(new VectorDrawable());
349         when(mPackageManager.getApplicationLabel(any())).thenReturn(TEST_MDM_PACKAGE_LABEL);
350         when(mPackageManager.resolveActivity(any(), anyInt())).thenReturn(new ResolveInfo());
351 
352         when(mKeyguardManager.inKeyguardRestrictedInputMode()).thenReturn(false);
353         when(mDevicePolicyManager.getStorageEncryptionStatus())
354                 .thenReturn(DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE);
355         when(mSettingsFacade.isDuringSetupWizard(mContext)).thenReturn(false);
356 
357         mViewModel = new PreProvisioningViewModel(
358                 mTimeLogger,
359                 mMessageParser,
360                 mEncryptionController, new PreProvisioningViewModel.DefaultConfig());
361 
362         mController = createControllerWithRoleHolderUpdaterNotPresent();
363 
364         disableRoleHolderDelegation();
365     }
366 
createControllerWithRoleHolderHelpers( DeviceManagementRoleHolderHelper deviceManagementRoleHolderHelper, DeviceManagementRoleHolderUpdaterHelper roleHolderUpdaterHelper)367     private PreProvisioningActivityController createControllerWithRoleHolderHelpers(
368             DeviceManagementRoleHolderHelper deviceManagementRoleHolderHelper,
369             DeviceManagementRoleHolderUpdaterHelper roleHolderUpdaterHelper) {
370         return new PreProvisioningActivityController(
371                 mContext,
372                 mUi,
373                 mUtils,
374                 mSettingsFacade,
375                 mSharedPreferences,
376                 new PolicyComplianceUtils(),
377                 new GetProvisioningModeUtils(),
378                 mViewModel,
379                 (context, provisioningId) -> parcelables -> DISCLAIMERS_PARAM,
380                 deviceManagementRoleHolderHelper,
381                 roleHolderUpdaterHelper);
382     }
383 
384     @Test
testManagedProfile()385     public void testManagedProfile() throws Exception {
386         // GIVEN an intent to provision a managed profile
387         prepareMocksForManagedProfileIntent(false);
388         // WHEN initiating provisioning
389         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
390                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
391         // THEN the UI elements should be updated accordingly
392         verifyInitiateProfileOwnerUi();
393         // WHEN the user consents
394         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
395                 mController.continueProvisioningAfterUserConsent());
396         // THEN start profile provisioning
397         verify(mUi).onParamsValidated(mParams);
398         verify(mUi).startProvisioning(mParams);
399         verify(mEncryptionController).cancelEncryptionReminder();
400         verifyNoMoreInteractions(mUi);
401     }
402 
403     @Test
testManagedProfile_hasRoleHolderUpdaterInstalled_startsRoleHolderUpdater()404     public void testManagedProfile_hasRoleHolderUpdaterInstalled_startsRoleHolderUpdater()
405             throws Exception {
406         enableRoleHolderDelegation();
407         mController = createControllerWithRoleHolderUpdaterInstalled();
408         // GIVEN an intent to provision a managed profile
409         prepareMocksForManagedProfileIntent(false);
410         // WHEN initiating provisioning
411         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
412                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
413         verify(mUi).onParamsValidated(mParams);
414         // THEN start profile provisioning
415         verify(mUi).startRoleHolderUpdater(/* isRoleHolderRequestedUpdate= */ false);
416         verifyNoMoreInteractions(mUi);
417     }
418 
419     @Test
testManagedProfile_hasRoleHolderValidAndInstalled_updaterNotInstalled_startsRoleHolder()420     public void testManagedProfile_hasRoleHolderValidAndInstalled_updaterNotInstalled_startsRoleHolder()
421             throws Exception {
422         enableRoleHolderDelegation();
423         mController = createControllerWithRoleHolderValidAndInstalledWithUpdater(
424                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_INSTALLED);
425         // GIVEN an intent to provision a managed profile
426         prepareMocksForManagedProfileIntent(false);
427         // WHEN initiating provisioning
428         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
429             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
430         });
431 
432         // THEN start role holder provisioning
433         verify(mUi).onParamsValidated(mParams);
434         verify(mUi).startRoleHolderProvisioning(any(Intent.class));
435         verifyNoMoreInteractions(mUi);
436         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
437         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(true);
438     }
439 
440     @Test
testTrustedSource_roleHolderDownloadExtra_downloadsRoleHolder()441     public void testTrustedSource_roleHolderDownloadExtra_downloadsRoleHolder() throws Exception {
442         enableRoleHolderDelegation();
443         when(mSettingsFacade.isDuringSetupWizard(any())).thenReturn(false);
444         mController = createControllerWithRoleHolderHelpers(
445                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT,
446                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_INSTALLED);
447 
448         // GIVEN an intent to provision via trusted source
449         prepareMocksForTrustedSourceIntent(DOWNLOAD_ROLE_HOLDER_PARAMS);
450 
451         // WHEN initiating provisioning
452         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
453             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
454         });
455 
456         // THEN download role holder
457         verify(mUi).onParamsValidated(DOWNLOAD_ROLE_HOLDER_PARAMS);
458         verify(mUi).startPlatformDrivenRoleHolderDownload();
459         verifyNoMoreInteractions(mUi);
460     }
461 
462     @Test
testManagedProfile_roleHolderDownloadExtraAndAllowOffline_startsPlatformProvidedProvisioning()463     public void testManagedProfile_roleHolderDownloadExtraAndAllowOffline_startsPlatformProvidedProvisioning()
464             throws Exception {
465         enableRoleHolderDelegation();
466         when(mSettingsFacade.isDuringSetupWizard(any())).thenReturn(false);
467         mController = createControllerWithRoleHolderHelpers(
468                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT,
469                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_INSTALLED);
470 
471         // GIVEN an intent to provision via trusted source
472         prepareMocksForManagedProfileIntent(DOWNLOAD_ROLE_HOLDER_PARAMS_WITH_ALLOW_OFFLINE);
473 
474         // WHEN initiating provisioning
475         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
476             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
477         });
478 
479         // THEN start profile provisioning
480         verify(mUi).onParamsValidated(DOWNLOAD_ROLE_HOLDER_PARAMS_WITH_ALLOW_OFFLINE);
481         verify(mUi).initiateUi(any(UiParams.class));
482         verifyNoMoreInteractions(mUi);
483         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
484     }
485 
486     @Test
testManagedProfile_noRoleHolderAndRoleHolderDownloadExtra_failsProvisioning()487     public void testManagedProfile_noRoleHolderAndRoleHolderDownloadExtra_failsProvisioning()
488             throws Exception {
489         enableRoleHolderDelegation();
490         when(mSettingsFacade.isDuringSetupWizard(any())).thenReturn(false);
491         mController = createControllerWithRoleHolderHelpers(
492                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT,
493                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_INSTALLED);
494 
495         // GIVEN an intent to provision via trusted source
496         prepareMocksForManagedProfileIntent(DOWNLOAD_ROLE_HOLDER_PARAMS);
497 
498         // WHEN initiating provisioning
499         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
500             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
501         });
502 
503         // THEN start profile provisioning
504         verify(mUi).onParamsValidated(DOWNLOAD_ROLE_HOLDER_PARAMS);
505         verify(mUi).showErrorAndClose(any(), anyInt(), anyString());
506         verifyNoMoreInteractions(mUi);
507         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
508     }
509 
510     @Test
testManagedProfile_hasRoleHolderValidAndInstalled_updaterNotDefined_startsRoleHolder()511     public void testManagedProfile_hasRoleHolderValidAndInstalled_updaterNotDefined_startsRoleHolder()
512             throws Exception {
513         enableRoleHolderDelegation();
514         mController = createControllerWithRoleHolderValidAndInstalledWithUpdater(
515                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_DEFINED);
516         // GIVEN an intent to provision a managed profile
517         prepareMocksForManagedProfileIntent(false);
518         // WHEN initiating provisioning
519         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
520             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
521         });
522 
523         // THEN start role holder provisioning
524         verify(mUi).onParamsValidated(any());
525         verify(mUi).startRoleHolderProvisioning(any(Intent.class));
526         verifyNoMoreInteractions(mUi);
527         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
528         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(true);
529     }
530 
531     @Test
testManagedProfile_roleHolderStarted_startedWithoutState()532     public void testManagedProfile_roleHolderStarted_startedWithoutState()
533             throws Exception {
534         enableRoleHolderDelegation();
535         mController = createControllerWithRoleHolderValidAndInstalledWithUpdater(
536                 ROLE_HOLDER_UPDATER_HELPER);
537         // GIVEN an intent to provision a managed profile
538         prepareMocksForManagedProfileIntent(false);
539         // WHEN initiating provisioning
540         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
541             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
542 
543             // simulate that the updater has run and returned back, starting DMRH
544             mController.startAppropriateProvisioning(
545                     mIntent, ADDITIONAL_EXTRAS_DEFAULT, TEST_CALLING_PACKAGE);
546         });
547 
548         // THEN start profile provisioning
549         ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
550         verify(mUi).onParamsValidated(any());
551         verify(mUi).startRoleHolderUpdater(false);
552         verify(mUi).startRoleHolderProvisioning(intentArgumentCaptor.capture());
553         assertThat(intentArgumentCaptor.getValue().hasExtra(EXTRA_ROLE_HOLDER_STATE)).isFalse();
554         verifyNoMoreInteractions(mUi);
555     }
556 
557     @Test
testManagedProfile_withoutRoleHolderUpdaterAndNoRoleHolderInstalled_startsPlatformProvidedProvisioning()558     public void testManagedProfile_withoutRoleHolderUpdaterAndNoRoleHolderInstalled_startsPlatformProvidedProvisioning()
559             throws Exception {
560         enableRoleHolderDelegation();
561         mController = createControllerWithRoleHolderHelpers(
562                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_CONFIGURED,
563                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_DEFINED);
564         // GIVEN an intent to provision a managed profile
565         prepareMocksForManagedProfileIntent(false);
566         // WHEN initiating provisioning
567         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
568             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
569         });
570 
571         // THEN start profile provisioning
572         verify(mUi).onParamsValidated(mParams);
573         verify(mUi).initiateUi(any(UiParams.class));
574         verifyNoMoreInteractions(mUi);
575         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
576     }
577 
578     @Test
testFinancedDevice_provisioningStarted()579     public void testFinancedDevice_provisioningStarted()
580             throws Exception {
581         enableRoleHolderDelegation();
582         mController = createControllerWithRoleHolderValidAndInstalledWithUpdater(
583                 ROLE_HOLDER_UPDATER_HELPER);
584         // GIVEN an intent to provision a managed profile
585         prepareMocksForFinancedDeviceIntent();
586         // WHEN initiating provisioning
587         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
588             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
589         });
590 
591         // THEN start financed device provisioning
592         verify(mUi).onParamsValidated(any());
593         verify(mUi).prepareFinancedDeviceFlow(any(ProvisioningParams.class));
594         verifyNoMoreInteractions(mUi);
595         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
596     }
597 
598     @Test
testManagedProfile_roleHolderRequestedUpdate_restartsWithProvidedState()599     public void testManagedProfile_roleHolderRequestedUpdate_restartsWithProvidedState()
600             throws Exception {
601         enableRoleHolderDelegation();
602         mController = createControllerWithRoleHolderValidAndInstalledWithUpdater(
603                 ROLE_HOLDER_UPDATER_HELPER);
604         // GIVEN an intent to provision a managed profile
605         prepareMocksForManagedProfileIntent(false);
606         // WHEN initiating provisioning
607         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
608             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
609 
610             // simulate that the updater has run and returned back, starting DMRH
611             mController.startAppropriateProvisioning(
612                     mIntent, ADDITIONAL_EXTRAS_DEFAULT, TEST_CALLING_PACKAGE);
613 
614             // simulate that DMRH has returned RESULT_UPDATE_ROLE_HOLDER with state
615             mController.startRoleHolderUpdater(
616                     /* isRoleHolderRequestedUpdate= */ true, ROLE_HOLDER_STATE);
617 
618             // simulate that DMRH updater updated DMRH and now it restarts it with
619             // state returned before
620             mController.startAppropriateProvisioning(
621                     mIntent, ADDITIONAL_EXTRAS_SUCCESSFUL_UPDATE, TEST_CALLING_PACKAGE);
622         });
623 
624         // THEN start profile provisioning
625         verify(mUi).onParamsValidated(any());
626         verify(mUi).startRoleHolderUpdater(false);
627         verify(mUi).startRoleHolderUpdater(true);
628         ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
629         verify(mUi, times(2)).startRoleHolderProvisioning(intentArgumentCaptor.capture());
630         Intent resultIntent = intentArgumentCaptor.getAllValues().get(1);
631         assertBundlesEqual(
632                 resultIntent.getParcelableExtra(EXTRA_ROLE_HOLDER_STATE),
633                 ROLE_HOLDER_STATE);
634         assertThat(resultIntent.getIntExtra(EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE, RESULT_CANCELED))
635                 .isEqualTo(RESULT_OK);
636         verifyNoMoreInteractions(mUi);
637     }
638 
639     @Test
testManagedProfile_roleHolderRequestedUpdate_updateFailsOnce_restartsWithProvidedState()640     public void testManagedProfile_roleHolderRequestedUpdate_updateFailsOnce_restartsWithProvidedState()
641             throws Exception {
642         enableRoleHolderDelegation();
643         mController = createControllerWithRoleHolderValidAndInstalledWithUpdater(
644                 ROLE_HOLDER_UPDATER_HELPER);
645         // GIVEN an intent to provision a managed profile
646         prepareMocksForManagedProfileIntent(false);
647         // WHEN initiating provisioning
648         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
649             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
650 
651             // simulate that the updater has run and returned back, starting DMRH
652             mController.startAppropriateProvisioning(
653                     mIntent, ADDITIONAL_EXTRAS_DEFAULT, TEST_CALLING_PACKAGE);
654 
655             // simulate that DMRH has returned RESULT_UPDATE_ROLE_HOLDER with state
656             mController.startRoleHolderUpdater(
657                     /* isRoleHolderRequestedUpdate= */ true, ROLE_HOLDER_STATE);
658 
659             // simulate that DMRH updater failed and starts again with last state
660             mController.startRoleHolderUpdaterWithLastState(
661                     /* isRoleHolderRequestedUpdate= */ true);
662 
663             // simulate that DMRH updater updated DMRH and now it restarts it with
664             // state returned before
665             mController.startAppropriateProvisioning(
666                     mIntent, ADDITIONAL_EXTRAS_SUCCESSFUL_UPDATE, TEST_CALLING_PACKAGE);
667         });
668 
669         // THEN start profile provisioning
670         verify(mUi).onParamsValidated(any());
671         ArgumentCaptor<Boolean> booleanArgumentCaptor = ArgumentCaptor.forClass(Boolean.class);
672         verify(mUi, times(3)).startRoleHolderUpdater(booleanArgumentCaptor.capture());
673         assertThat(booleanArgumentCaptor.getAllValues().get(0)).isFalse();
674         assertThat(booleanArgumentCaptor.getAllValues().get(1)).isTrue();
675         assertThat(booleanArgumentCaptor.getAllValues().get(2)).isTrue();
676         ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
677         verify(mUi, times(2)).startRoleHolderProvisioning(intentArgumentCaptor.capture());
678         Intent resultIntent = intentArgumentCaptor.getAllValues().get(1);
679         assertBundlesEqual(
680                 resultIntent.getParcelableExtra(EXTRA_ROLE_HOLDER_STATE),
681                 ROLE_HOLDER_STATE);
682         assertThat(resultIntent.getIntExtra(EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE, RESULT_CANCELED))
683                 .isEqualTo(RESULT_OK);
684         verifyNoMoreInteractions(mUi);
685     }
686 
687     @Test
testManagedProfile_roleHolderReady_startsRoleHolderProvisioning()688     public void testManagedProfile_roleHolderReady_startsRoleHolderProvisioning()
689             throws Exception {
690         enableRoleHolderDelegation();
691         mController = createControllerWithRoleHolderHelpers(
692                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER,
693                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_DEFINED);
694         // GIVEN an intent to provision a managed profile
695         prepareMocksForManagedProfileIntent(false);
696         // WHEN initiating provisioning
697         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
698             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
699         });
700 
701         // THEN start profile provisioning
702         verify(mUi).onParamsValidated(mParams);
703         verify(mUi).startRoleHolderProvisioning(any(Intent.class));
704         verifyNoMoreInteractions(mUi);
705         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
706     }
707 
708     @Test
testManagedProfile_allowOffline_startsPlatformProvidedProvisioning()709     public void testManagedProfile_allowOffline_startsPlatformProvidedProvisioning()
710             throws Exception {
711         enableRoleHolderDelegation();
712         mController = createControllerWithRoleHolderHelpers(
713                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT,
714                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_DEFINED);
715         // GIVEN an intent to provision a managed profile
716         prepareMocksForManagedProfileIntent(ALLOW_OFFLINE_PARAMS);
717         // WHEN initiating provisioning
718         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
719             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
720         });
721 
722         // THEN start profile provisioning
723         verify(mUi).onParamsValidated(ALLOW_OFFLINE_PARAMS);
724         verify(mUi).initiateUi(any(UiParams.class));
725         verifyNoMoreInteractions(mUi);
726         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
727     }
728 
729     @Test
testManagedProfile_roleHolderNotConfigured_startsPlatformProvidedProvisioning()730     public void testManagedProfile_roleHolderNotConfigured_startsPlatformProvidedProvisioning()
731             throws Exception {
732         enableRoleHolderDelegation();
733         mController = createControllerWithRoleHolderHelpers(
734                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_CONFIGURED,
735                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_DEFINED);
736         // GIVEN an intent to provision a managed profile
737         prepareMocksForManagedProfileIntent(false);
738         // WHEN initiating provisioning
739         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
740             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
741         });
742 
743         // THEN start profile provisioning
744         verify(mUi).onParamsValidated(mParams);
745         verify(mUi).initiateUi(any(UiParams.class));
746         verifyNoMoreInteractions(mUi);
747         verify(mSharedPreferences).setIsProvisioningFlowDelegatedToRoleHolder(false);
748     }
749 
750     @Test
testManagedProfile_provisioningNotAllowed()751     public void testManagedProfile_provisioningNotAllowed() throws Exception {
752         // GIVEN an intent to provision a managed profile, but provisioning mode is not allowed
753         prepareMocksForManagedProfileIntent(false);
754         when(mDevicePolicyManager.checkProvisioningPrecondition(
755                 ACTION_PROVISION_MANAGED_PROFILE, TEST_MDM_PACKAGE))
756                 .thenReturn(STATUS_MANAGED_USERS_NOT_SUPPORTED);
757         when(mContext.getContentResolver()).thenReturn(mContentResolver);
758         when(mContentInterface.call(anyString(), anyString(), any(), any()))
759                 .thenReturn(GET_DEVICE_NAME_BUNDLE);
760         // WHEN initiating provisioning
761         mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
762         // THEN show an error dialog
763         verify(mUi).showErrorAndClose(
764                 eq(LazyStringResource.of(R.string.cant_add_work_profile)),
765                 eq(LazyStringResource.of(
766                         R.string.work_profile_cant_be_added_contact_admin, DEFAULT_DEVICE_NAME)),
767                 any());
768         verifyNoMoreInteractions(mUi);
769     }
770 
771     @Test
testManagedProfile_nullCallingPackage()772     public void testManagedProfile_nullCallingPackage() throws Exception {
773         // GIVEN a device that is not currently encrypted
774         prepareMocksForManagedProfileIntent(false);
775         // WHEN initiating provisioning
776         mController.initiateProvisioning(mIntent, null);
777         // THEN error is shown
778         verify(mUi).showErrorAndClose(eq(R.string.cant_set_up_device),
779                 eq(R.string.contact_your_admin_for_help), any(String.class));
780         verifyNoMoreInteractions(mUi);
781     }
782 
783     @Test
testManagedProfile_invalidCallingPackage()784     public void testManagedProfile_invalidCallingPackage() throws Exception {
785         // GIVEN a device that is not currently encrypted
786         prepareMocksForManagedProfileIntent(false);
787         // WHEN initiating provisioning
788         mController.initiateProvisioning(mIntent, "com.android.invalid.dpc");
789         // THEN error is shown
790         verify(mUi).showErrorAndClose(eq(R.string.cant_set_up_device),
791                 eq(R.string.contact_your_admin_for_help), any(String.class));
792         verifyNoMoreInteractions(mUi);
793     }
794 
795     @Test
testManagedProfile_withEncryption()796     public void testManagedProfile_withEncryption() throws Exception {
797         // GIVEN a device that is not currently encrypted
798         prepareMocksForManagedProfileIntent(false);
799         when(mUtils.isEncryptionRequired()).thenReturn(true);
800         // WHEN initiating managed profile provisioning
801         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
802                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
803         verify(mUi).onParamsValidated(mParams);
804         // WHEN the user consents
805         mController.continueProvisioningAfterUserConsent();
806         // THEN the UI elements should be updated accordingly
807         verifyInitiateProfileOwnerUi();
808         // THEN show encryption screen
809         verify(mUi).requestEncryption(mParams);
810         verifyNoMoreInteractions(mUi);
811     }
812 
813     @Test
testManagedProfile_afterEncryption()814     public void testManagedProfile_afterEncryption() throws Exception {
815         // GIVEN managed profile provisioning continues after successful encryption. In this case
816         // we don't set the startedByTrustedSource flag.
817         prepareMocksForAfterEncryption(ACTION_PROVISION_MANAGED_PROFILE, false);
818         // WHEN initiating with a continuation intent
819         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
820                 mController.initiateProvisioning(mIntent, MP_PACKAGE_NAME));
821         verify(mUi).onParamsValidated(mParams);
822         // THEN the UI elements should be updated accordingly
823         verifyInitiateProfileOwnerUi();
824         // WHEN the user consents
825         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
826                 mController.continueProvisioningAfterUserConsent());
827         // THEN start profile provisioning
828         verify(mUi).onParamsValidated(mParams);
829         verify(mUi).startProvisioning(mParams);
830         verify(mEncryptionController).cancelEncryptionReminder();
831         verifyNoMoreInteractions(mUi);
832     }
833 
834     @Test
testManagedProfile_badLauncher()835     public void testManagedProfile_badLauncher() throws Exception {
836         // GIVEN that the current launcher does not support managed profiles
837         prepareMocksForManagedProfileIntent(false);
838         when(mUtils.currentLauncherSupportsManagedProfiles(mContext)).thenReturn(false);
839         // WHEN initiating managed profile provisioning
840         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
841                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
842         verify(mUi).onParamsValidated(mParams);
843         // THEN the UI elements should be updated accordingly
844         verifyInitiateProfileOwnerUi();
845         // WHEN the user consents
846         mController.continueProvisioningAfterUserConsent();
847         // THEN show a dialog indicating that the current launcher is invalid
848         verify(mUi).showCurrentLauncherInvalid();
849         verifyNoMoreInteractions(mUi);
850     }
851 
852     @Test
testManagedProfile_wrongPackage()853     public void testManagedProfile_wrongPackage() throws Exception {
854         // GIVEN that the provisioning intent tries to set a package different from the caller
855         // as owner of the profile
856         prepareMocksForManagedProfileIntent(false);
857         // WHEN initiating managed profile provisioning
858         mController.initiateProvisioning(mIntent, TEST_BOGUS_PACKAGE);
859         // THEN show an error dialog and do not continue
860         verify(mUi).showErrorAndClose(eq(R.string.cant_set_up_device),
861                 eq(R.string.contact_your_admin_for_help), any());
862         verifyNoMoreInteractions(mUi);
863     }
864 
865     @Test
testManagedProfile_frp()866     public void testManagedProfile_frp() throws Exception {
867         // GIVEN managed profile provisioning is invoked from SUW with FRP active
868         prepareMocksForManagedProfileIntent(false);
869         when(mSettingsFacade.isDeviceProvisioned(mContext)).thenReturn(false);
870         // setting the data block size to any number greater than 0 should invoke FRP.
871         when(mPdbManager.getDataBlockSize()).thenReturn(4);
872         when(mContext.getContentResolver()).thenReturn(mContentResolver);
873         when(mContentInterface.call(anyString(), anyString(), any(), any()))
874                 .thenReturn(GET_DEVICE_NAME_BUNDLE);
875         // WHEN initiating managed profile provisioning
876         mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
877         // THEN show an error dialog and do not continue
878         verify(mUi).showErrorAndClose(
879                 eq(LazyStringResource.of(R.string.cant_set_up_device)),
880                 eq(LazyStringResource.of(R.string.device_has_reset_protection_contact_admin,
881                         DEFAULT_DEVICE_NAME)),
882                 any());
883         verifyNoMoreInteractions(mUi);
884     }
885 
886     @Test
testCheckFactoryResetProtection_skipFrp()887     public void testCheckFactoryResetProtection_skipFrp() throws Exception {
888         // GIVEN managed profile provisioning is invoked from SUW with FRP active
889         when(mSettingsFacade.isDeviceProvisioned(mContext)).thenReturn(false);
890         // setting the data block size to any number greater than 0 to simulate FRP.
891         when(mPdbManager.getDataBlockSize()).thenReturn(4);
892         // GIVEN there is a persistent data package.
893         when(mContext.getResources()).thenReturn(mResources);
894         when(mResources.getString(anyInt())).thenReturn("test.persistent.data");
895         // GIVEN the persistent data package is a system app.
896         PackageInfo packageInfo = new PackageInfo();
897         ApplicationInfo applicationInfo = new ApplicationInfo();
898         applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
899         packageInfo.applicationInfo = applicationInfo;
900         when(mPackageManager.getPackageInfo(eq("test.persistent.data"), anyInt()))
901                 .thenReturn(packageInfo);
902 
903         // WHEN factory reset protection is checked for trusted source device provisioning.
904         ProvisioningParams provisioningParams = createParams(true, false, null,
905                 ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE, TEST_MDM_PACKAGE);
906         boolean result = mController.checkFactoryResetProtection(
907                 provisioningParams, "test.persistent.data");
908 
909         // THEN the check is successful despite the FRP data presence.
910         assertThat(result).isTrue();
911     }
912 
913     @Test
testManagedProfile_skipEncryption()914     public void testManagedProfile_skipEncryption() throws Exception {
915         // GIVEN an intent to provision a managed profile with skip encryption
916         prepareMocksForManagedProfileIntent(true);
917         when(mUtils.isEncryptionRequired()).thenReturn(true);
918         // WHEN initiating provisioning
919         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
920                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
921         verify(mUi).onParamsValidated(mParams);
922         // THEN the UI elements should be updated accordingly
923         verifyInitiateProfileOwnerUi();
924         // WHEN the user consents
925         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
926                 mController.continueProvisioningAfterUserConsent());
927         // THEN start profile provisioning
928         verify(mUi).onParamsValidated(mParams);
929         verify(mUi).startProvisioning(mParams);
930         verify(mUi, never()).requestEncryption(any(ProvisioningParams.class));
931         verify(mEncryptionController).cancelEncryptionReminder();
932         verifyNoMoreInteractions(mUi);
933     }
934 
935     @Test
testManagedProfile_encryptionNotSupported()936     public void testManagedProfile_encryptionNotSupported() throws Exception {
937         // GIVEN an intent to provision a managed profile on an unencrypted device that does not
938         // support encryption
939         prepareMocksForManagedProfileIntent(false);
940         when(mUtils.isEncryptionRequired()).thenReturn(true);
941         when(mDevicePolicyManager.getStorageEncryptionStatus())
942                 .thenReturn(DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED);
943         when(mContext.getContentResolver()).thenReturn(mContentResolver);
944         when(mContentInterface.call(anyString(), anyString(), any(), any()))
945                 .thenReturn(GET_DEVICE_NAME_BUNDLE);
946         // WHEN initiating provisioning
947         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
948                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
949         verify(mUi).onParamsValidated(mParams);
950         // WHEN the user consents
951         mController.continueProvisioningAfterUserConsent();
952         // THEN the UI elements should be updated accordingly
953         verifyInitiateProfileOwnerUi();
954         // THEN show an error indicating that this device does not support encryption
955         verify(mUi).showErrorAndClose(
956                 eq(LazyStringResource.of(R.string.cant_set_up_device)),
957                 eq(LazyStringResource.of(R.string.device_doesnt_allow_encryption_contact_admin,
958                         DEFAULT_DEVICE_NAME)),
959                 any());
960         verifyNoMoreInteractions(mUi);
961     }
962 
963     // TODO(b/177575786): Migrate outdated PreProvisioningControllerTest tests to robolectric
964     /*
965         @Test
966 public void testNfc_afterEncryption() throws Exception {
967         // GIVEN provisioning was started via an NFC tap and we have gone through encryption
968         // in this case the device gets resumed with the DO intent and startedByTrustedSource flag
969         // set
970         prepareMocksForAfterEncryption(ACTION_PROVISION_MANAGED_DEVICE, true);
971         // WHEN continuing NFC provisioning after encryption
972         mController.initiateProvisioning(mIntent, null, null);
973         // WHEN the user consents
974         mController.continueProvisioningAfterUserConsent();
975         // THEN start device owner provisioning
976         verifyInitiateDeviceOwnerUi();
977         verify(mUi).startProvisioning(mUserManager.getUserHandle(), mParams);
978         verifyNoMoreInteractions(mUi);
979     }
980 
981         @Test
982 public void testQr() throws Exception {
983         // GIVEN provisioning was started via a QR code and device is already encrypted
984         prepareMocksForQrIntent(ACTION_PROVISION_MANAGED_DEVICE, false);
985         // WHEN initiating QR provisioning
986         mController.initiateProvisioning(mIntent, null, null);
987         // WHEN the user consents
988         mController.continueProvisioningAfterUserConsent();
989         // THEN start device owner provisioning
990         verifyInitiateDeviceOwnerUi();
991         verify(mUi).startProvisioning(mUserManager.getUserHandle(), mParams);
992         verifyNoMoreInteractions(mUi);
993     }
994 
995         @Test
996 public void testQr_skipEncryption() throws Exception {
997         // GIVEN provisioning was started via a QR code with encryption skipped
998         prepareMocksForQrIntent(ACTION_PROVISION_MANAGED_DEVICE, true);
999         when(mUtils.isEncryptionRequired()).thenReturn(true);
1000         // WHEN initiating QR provisioning
1001         mController.initiateProvisioning(mIntent, null, null);
1002         // WHEN the user consents
1003         mController.continueProvisioningAfterUserConsent();
1004         // THEN start device owner provisioning
1005         verifyInitiateDeviceOwnerUi();
1006         verify(mUi).startProvisioning(mUserManager.getUserHandle(), mParams);
1007         verify(mUi, never()).requestEncryption(any());
1008         verifyNoMoreInteractions(mUi);
1009     }
1010 
1011         @Test
1012 public void testQr_withEncryption() throws Exception {
1013         // GIVEN provisioning was started via a QR code with encryption necessary
1014         prepareMocksForQrIntent(ACTION_PROVISION_MANAGED_DEVICE, false);
1015         when(mUtils.isEncryptionRequired()).thenReturn(true);
1016         // WHEN initiating QR provisioning
1017         mController.initiateProvisioning(mIntent, null, null);
1018         // WHEN the user consents
1019         mController.continueProvisioningAfterUserConsent();
1020         // THEN show encryption screen
1021         verifyInitiateDeviceOwnerUi();
1022         verify(mUi).requestEncryption(mParams);
1023         verifyNoMoreInteractions(mUi);
1024     }
1025 
1026         @Test
1027 public void testQr_frp() throws Exception {
1028         // GIVEN provisioning was started via a QR code, but the device is locked with FRP
1029         prepareMocksForQrIntent(ACTION_PROVISION_MANAGED_DEVICE, false);
1030         // setting the data block size to any number greater than 0 should invoke FRP.
1031         when(mPdbManager.getDataBlockSize()).thenReturn(4);
1032         // WHEN initiating QR provisioning
1033         mController.initiateProvisioning(mIntent, null, null);
1034         // THEN show an error dialog
1035         verify(mUi).showErrorAndClose(eq(R.string.cant_set_up_device),
1036                 eq(R.string.device_has_reset_protection_contact_admin), any());
1037         verifyNoMoreInteractions(mUi);
1038     }
1039 
1040         @Test
1041 public void testDeviceOwner() throws Exception {
1042         // GIVEN device owner provisioning was started and device is already encrypted
1043         prepareMocksForDoIntent(true);
1044         // WHEN initiating provisioning
1045         mController.initiateProvisioning(mIntent, null, TEST_MDM_PACKAGE);
1046         // THEN the UI elements should be updated accordingly
1047         verifyInitiateDeviceOwnerUi();
1048         // WHEN the user consents
1049         mController.continueProvisioningAfterUserConsent();
1050         // THEN start device owner provisioning
1051         verify(mUi).startProvisioning(mUserManager.getUserHandle(), mParams);
1052         verify(mEncryptionController).cancelEncryptionReminder();
1053         verifyNoMoreInteractions(mUi);
1054     }
1055 
1056         @Test
1057 public void testDeviceOwner_skipEncryption() throws Exception {
1058         // GIVEN device owner provisioning was started with skip encryption flag
1059         prepareMocksForDoIntent(true);
1060         when(mUtils.isEncryptionRequired()).thenReturn(true);
1061         // WHEN initiating provisioning
1062         mController.initiateProvisioning(mIntent, null, TEST_MDM_PACKAGE);
1063         // THEN the UI elements should be updated accordingly
1064         verifyInitiateDeviceOwnerUi();
1065         // WHEN the user consents
1066         mController.continueProvisioningAfterUserConsent();
1067         // THEN start device owner provisioning
1068         verify(mUi).startProvisioning(mUserManager.getUserHandle(), mParams);
1069         verify(mUi, never()).requestEncryption(any());
1070         verify(mEncryptionController).cancelEncryptionReminder();
1071         verifyNoMoreInteractions(mUi);
1072     }
1073 
1074     // TODO: There is a difference in behaviour here between the managed profile and the device
1075     // owner case: In managed profile case, we invoke encryption after user clicks next, but in
1076     // device owner mode we invoke it straight away. Also in theory no need to update
1077     // the UI elements if we're moving away from this activity straight away.
1078         @Test
1079 public void testDeviceOwner_withEncryption() throws Exception {
1080         // GIVEN device owner provisioning is started with encryption needed
1081         prepareMocksForDoIntent(false);
1082         when(mUtils.isEncryptionRequired()).thenReturn(true);
1083         // WHEN initiating provisioning
1084         mController.initiateProvisioning(mIntent, null, TEST_MDM_PACKAGE);
1085         // WHEN the user consents
1086         mController.continueProvisioningAfterUserConsent();
1087         // THEN update the UI elements and show encryption screen
1088         verifyInitiateDeviceOwnerUi();
1089         verify(mUi).requestEncryption(mParams);
1090         verifyNoMoreInteractions(mUi);
1091     }
1092 
1093         @Test
1094 public void testDeviceOwner_afterEncryption() throws Exception {
1095         // GIVEN device owner provisioning is continued after encryption. In this case we do not set
1096         // the startedByTrustedSource flag.
1097         prepareMocksForAfterEncryption(ACTION_PROVISION_MANAGED_DEVICE, false);
1098         // WHEN provisioning is continued
1099         mController.initiateProvisioning(mIntent, null, null);
1100         // THEN the UI elements should be updated accordingly
1101         verifyInitiateDeviceOwnerUi();
1102         // WHEN the user consents
1103         mController.continueProvisioningAfterUserConsent();
1104         // THEN start device owner provisioning
1105         verify(mUi).startProvisioning(mUserManager.getUserHandle(), mParams);
1106         verify(mEncryptionController).cancelEncryptionReminder();
1107         verifyNoMoreInteractions(mUi);
1108     }
1109 
1110         @Test
1111 public void testDeviceOwner_frp() throws Exception {
1112         // GIVEN device owner provisioning is invoked with FRP active
1113         prepareMocksForDoIntent(false);
1114         // setting the data block size to any number greater than 0 should invoke FRP.
1115         when(mPdbManager.getDataBlockSize()).thenReturn(4);
1116         // WHEN initiating provisioning
1117         mController.initiateProvisioning(mIntent, null, TEST_MDM_PACKAGE);
1118         // THEN show an error dialog
1119         verify(mUi).showErrorAndClose(eq(R.string.cant_set_up_device),
1120                 eq(R.string.device_has_reset_protection_contact_admin), any());
1121         verifyNoMoreInteractions(mUi);
1122     }*/
1123 
1124     @Test
testParamsNotLoaded_throwsException()1125     public void testParamsNotLoaded_throwsException() {
1126         assertThrows(IllegalStateException.class, () -> mController.getParams());
1127     }
1128 
1129     @Test
testInitiateProvisioning_showsWifiPicker()1130     public void testInitiateProvisioning_showsWifiPicker() {
1131         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1132                 .build();
1133         initiateProvisioning(params);
1134         verify(mUi).requestWifiPick();
1135     }
1136 
1137     @Test
testInitiateProvisioning_useMobileData_showsWifiPicker()1138     public void testInitiateProvisioning_useMobileData_showsWifiPicker() {
1139         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1140                 .setUseMobileData(true)
1141                 .build();
1142         initiateProvisioning(params);
1143         verify(mUi).requestWifiPick();
1144     }
1145 
1146     @Test
testInitiateProvisioning_useMobileData_noWifiPicker()1147     public void testInitiateProvisioning_useMobileData_noWifiPicker() {
1148         when(mUtils.isMobileNetworkConnectedToInternet(mContext)).thenReturn(true);
1149         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1150                 .setUseMobileData(true)
1151                 .build();
1152         initiateProvisioning(params);
1153         verify(mUi, never()).requestWifiPick();
1154     }
1155 
1156     @Test
testInitiateProvisioning_connectedToWifiOrEthernet_noWifiPicker()1157     public void testInitiateProvisioning_connectedToWifiOrEthernet_noWifiPicker() {
1158         when(mUtils.getActiveNetworkCapabilities(any())).thenReturn(new NetworkCapabilities());
1159         when(mUtils.isNetworkConnectedToInternetViaWiFi(any())).thenReturn(true);
1160 
1161         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1162                 .build();
1163         initiateProvisioning(params);
1164         verify(mUi, never()).requestWifiPick();
1165     }
1166 
1167     @Test
testInitiateProvisioning_noAdminDownloadInfo_noWifiPicker()1168     public void testInitiateProvisioning_noAdminDownloadInfo_noWifiPicker() {
1169         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1170                 .setDeviceAdminDownloadInfo(null)
1171                 .build();
1172         initiateProvisioning(params);
1173         verify(mUi, never()).requestWifiPick();
1174     }
1175 
1176     @Test
testInitiateProvisioning_wifiInfo_noWifiPicker()1177     public void testInitiateProvisioning_wifiInfo_noWifiPicker() {
1178         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1179                 .setWifiInfo(new WifiInfo.Builder().setSsid(TEST_WIFI_SSID).build())
1180                 .build();
1181         initiateProvisioning(params);
1182         verify(mUi, never()).requestWifiPick();
1183     }
1184 
1185     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_exactExtras()1186     public void testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_exactExtras() {
1187         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1188                 .setIsOrganizationOwnedProvisioning(true)
1189                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1190                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1191                         PROVISIONING_MODE_MANAGED_PROFILE,
1192                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1193                 )))
1194                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED)
1195                 .build();
1196         initiateProvisioning(params);
1197 
1198         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1199 
1200         assertThat(bundle.size()).isEqualTo(5);
1201     }
1202 
1203     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_imeiPassed()1204     public void testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_imeiPassed() {
1205         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1206                 .setIsOrganizationOwnedProvisioning(true)
1207                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1208                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1209                         PROVISIONING_MODE_MANAGED_PROFILE,
1210                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1211                 )))
1212                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED)
1213                 .build();
1214         initiateProvisioning(params);
1215 
1216         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1217 
1218         assertThat(bundle.getString(EXTRA_PROVISIONING_IMEI)).isEqualTo(TEST_IMEI);
1219     }
1220 
1221     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_serialNumberPassed()1222     public void testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_serialNumberPassed() {
1223         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1224                 .setIsOrganizationOwnedProvisioning(true)
1225                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1226                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1227                         PROVISIONING_MODE_MANAGED_PROFILE,
1228                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1229                 )))
1230                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED)
1231                 .build();
1232         initiateProvisioning(params);
1233 
1234         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1235 
1236         assertThat(bundle.containsKey(EXTRA_PROVISIONING_SERIAL_NUMBER)).isTrue();
1237     }
1238 
1239     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_nonOrgDevice_adminBundlePassed()1240     public void testGetAdditionalExtrasForGetProvisioningModeIntent_nonOrgDevice_adminBundlePassed() {
1241         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1242                 .setIsOrganizationOwnedProvisioning(false)
1243                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1244                 .setAllowedProvisioningModes(
1245                         new ArrayList<>(List.of(PROVISIONING_MODE_MANAGED_PROFILE)))
1246                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1247                 .build();
1248         initiateProvisioning(params);
1249 
1250         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1251 
1252         assertThat(bundle.keySet()).contains(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE);
1253         assertThat((PersistableBundle) bundle.getParcelable(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE))
1254                 .isEqualTo(TEST_ADMIN_BUNDLE);
1255     }
1256 
1257     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_nonOrgDevice_allowedModesPassed()1258     public void testGetAdditionalExtrasForGetProvisioningModeIntent_nonOrgDevice_allowedModesPassed() {
1259         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1260                 .setIsOrganizationOwnedProvisioning(false)
1261                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1262                 .setAllowedProvisioningModes(
1263                         new ArrayList<>(List.of(PROVISIONING_MODE_MANAGED_PROFILE)))
1264                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1265                 .build();
1266         initiateProvisioning(params);
1267 
1268         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1269 
1270         assertThat(bundle.getIntegerArrayList(EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES))
1271                 .containsExactly(PROVISIONING_MODE_MANAGED_PROFILE);
1272     }
1273 
1274     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_nonOrgDevice_hasExactlyTwoExtras()1275     public void testGetAdditionalExtrasForGetProvisioningModeIntent_nonOrgDevice_hasExactlyTwoExtras() {
1276         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1277                 .setIsOrganizationOwnedProvisioning(false)
1278                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1279                 .setAllowedProvisioningModes(
1280                         new ArrayList<>(List.of(PROVISIONING_MODE_MANAGED_PROFILE)))
1281                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1282                 .build();
1283         initiateProvisioning(params);
1284 
1285         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1286 
1287         assertThat(bundle.size()).isEqualTo(2);
1288     }
1289 
1290     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_adminBundlePassed()1291     public void testGetAdditionalExtrasForGetProvisioningModeIntent_orgDevice_adminBundlePassed() {
1292         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1293                 .setIsOrganizationOwnedProvisioning(true)
1294                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1295                 .build();
1296         initiateProvisioning(params);
1297 
1298         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1299 
1300         assertThat((PersistableBundle) bundle.getParcelable(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE))
1301                 .isEqualTo(TEST_ADMIN_BUNDLE);
1302     }
1303 
1304     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_adminBundlePassed()1305     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_adminBundlePassed() {
1306         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1307                 .setIsOrganizationOwnedProvisioning(true)
1308                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1309                 .setAllowedProvisioningModes(
1310                         new ArrayList<>(List.of(PROVISIONING_MODE_FULLY_MANAGED_DEVICE)))
1311                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_DEVICE_OWNER)
1312                 .build();
1313         initiateProvisioning(params);
1314 
1315         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1316 
1317         assertThat(bundle.keySet()).contains(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE);
1318         assertThat((PersistableBundle) bundle.getParcelable(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE))
1319                 .isEqualTo(TEST_ADMIN_BUNDLE);
1320     }
1321 
1322     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_exactExtras()1323     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_exactExtras() {
1324         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1325                 .setIsOrganizationOwnedProvisioning(true)
1326                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1327                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1328                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1329                 )))
1330                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_DEVICE_OWNER)
1331                 .build();
1332         initiateProvisioning(params);
1333 
1334         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1335 
1336         assertThat(bundle.size()).isEqualTo(5);
1337     }
1338 
1339     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_imeiPassed()1340     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_imeiPassed() {
1341         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1342                 .setIsOrganizationOwnedProvisioning(true)
1343                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1344                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1345                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1346                 )))
1347                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_DEVICE_OWNER)
1348                 .build();
1349         initiateProvisioning(params);
1350 
1351         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1352 
1353         assertThat(bundle.getString(EXTRA_PROVISIONING_IMEI)).isEqualTo(TEST_IMEI);
1354     }
1355 
1356     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_serialNumberPassed()1357     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManagedDevice_serialNumberPassed() {
1358         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1359                 .setIsOrganizationOwnedProvisioning(true)
1360                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1361                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1362                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1363                 )))
1364                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_DEVICE_OWNER)
1365                 .build();
1366         initiateProvisioning(params);
1367 
1368         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1369 
1370         assertThat(bundle.containsKey(EXTRA_PROVISIONING_SERIAL_NUMBER)).isTrue();
1371     }
1372 
1373     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManaged_hasOptOutExtra()1374     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManaged_hasOptOutExtra() {
1375         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1376                 .setIsOrganizationOwnedProvisioning(true)
1377                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1378                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1379                         PROVISIONING_MODE_MANAGED_PROFILE,
1380                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1381                 )))
1382                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED)
1383                 .build();
1384         initiateProvisioning(params);
1385 
1386         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1387 
1388         assertThat(bundle.getBoolean(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1389                 .isEqualTo(false);
1390     }
1391 
1392     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManaged_optOutExtraIsTrue()1393     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManaged_optOutExtraIsTrue() {
1394         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1395                 .setIsOrganizationOwnedProvisioning(true)
1396                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1397                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1398                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1399                 )))
1400                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_DEVICE_OWNER)
1401                 .setDeviceOwnerPermissionGrantOptOut(true)
1402                 .build();
1403         initiateProvisioning(params);
1404 
1405         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1406 
1407         assertThat(bundle.getBoolean(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1408                 .isEqualTo(true);
1409     }
1410 
1411     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfile_optOutExtraIsFalseByDefault()1412     public void testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfile_optOutExtraIsFalseByDefault() {
1413         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1414                 .setIsOrganizationOwnedProvisioning(false)
1415                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1416                 .setAllowedProvisioningModes(
1417                         new ArrayList<>(List.of(PROVISIONING_MODE_MANAGED_PROFILE)))
1418                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1419                 .build();
1420         initiateProvisioning(params);
1421 
1422         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1423 
1424         assertThat(bundle.containsKey(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1425                 .isEqualTo(false);
1426     }
1427 
1428     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManaged_optOutExtraIsFalse()1429     public void testGetAdditionalExtrasForGetProvisioningModeIntent_fullyManaged_optOutExtraIsFalse() {
1430         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1431                 .setIsOrganizationOwnedProvisioning(true)
1432                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1433                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1434                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
1435                 )))
1436                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_DEVICE_OWNER)
1437                 .setDeviceOwnerPermissionGrantOptOut(false)
1438                 .build();
1439         initiateProvisioning(params);
1440 
1441         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1442 
1443         assertThat(bundle.getBoolean(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1444                 .isEqualTo(false);
1445     }
1446 
1447     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfileByo_optOutExtraNotPresent()1448     public void testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfileByo_optOutExtraNotPresent() {
1449         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1450                 .setIsOrganizationOwnedProvisioning(false)
1451                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1452                 .setAllowedProvisioningModes(
1453                         new ArrayList<>(
1454                                 List.of(PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE)))
1455                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1456                 .build();
1457         initiateProvisioning(params);
1458 
1459         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1460 
1461         assertThat(bundle.containsKey(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1462                 .isEqualTo(false);
1463     }
1464 
1465     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfile_optOutExtraNotPresent()1466     public void testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfile_optOutExtraNotPresent() {
1467         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1468                 .setIsOrganizationOwnedProvisioning(false)
1469                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1470                 .setAllowedProvisioningModes(
1471                         new ArrayList<>(List.of(PROVISIONING_MODE_MANAGED_PROFILE)))
1472                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1473                 .setDeviceOwnerPermissionGrantOptOut(true)
1474                 .build();
1475         initiateProvisioning(params);
1476 
1477         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1478 
1479         assertThat(bundle.containsKey(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1480                 .isEqualTo(false);
1481     }
1482 
1483     @Test
testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfileByo_optOutExtraHasNoEffect()1484     public void testGetAdditionalExtrasForGetProvisioningModeIntent_managedProfileByo_optOutExtraHasNoEffect() {
1485         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1486                 .setIsOrganizationOwnedProvisioning(false)
1487                 .setAdminExtrasBundle(TEST_ADMIN_BUNDLE)
1488                 .setAllowedProvisioningModes(
1489                         new ArrayList<>(
1490                                 List.of(PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE)))
1491                 .setInitiatorRequestedProvisioningModes(FLAG_SUPPORTED_MODES_PERSONALLY_OWNED)
1492                 .setDeviceOwnerPermissionGrantOptOut(true)
1493                 .build();
1494         initiateProvisioning(params);
1495 
1496         Bundle bundle = mController.getAdditionalExtrasForGetProvisioningModeIntent();
1497 
1498         assertThat(bundle.containsKey(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT))
1499                 .isEqualTo(false);
1500     }
1501 
1502     @Test
testUpdateProvisioningParamsFromIntent_managedProfileModeWithAccountMigratedExtraTrue_setsParamToTrue()1503     public void testUpdateProvisioningParamsFromIntent_managedProfileModeWithAccountMigratedExtraTrue_setsParamToTrue() {
1504         Intent resultIntent = createResultIntentWithManagedProfile()
1505                 .putExtra(EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION, true);
1506         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1507                 .build();
1508         initiateProvisioning(params);
1509 
1510         mController.updateProvisioningParamsFromIntent(resultIntent);
1511 
1512         assertThat(mController.getParams().keepAccountMigrated).isTrue();
1513     }
1514 
1515     @Test
testUpdateProvisioningParamsFromIntent_managedProfileModeWithAccountMigratedExtraFalse_setsParamToFalse()1516     public void testUpdateProvisioningParamsFromIntent_managedProfileModeWithAccountMigratedExtraFalse_setsParamToFalse() {
1517         Intent resultIntent = createResultIntentWithManagedProfile()
1518                 .putExtra(EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION, false);
1519         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1520                 .build();
1521         initiateProvisioning(params);
1522 
1523         mController.updateProvisioningParamsFromIntent(resultIntent);
1524 
1525         assertThat(mController.getParams().keepAccountMigrated).isFalse();
1526     }
1527 
1528     @Test
testUpdateProvisioningParamsFromIntent_managedProfileMode_accountMigratedIsFalse()1529     public void testUpdateProvisioningParamsFromIntent_managedProfileMode_accountMigratedIsFalse() {
1530         Intent resultIntent = createResultIntentWithManagedProfile();
1531         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1532                 .build();
1533         initiateProvisioning(params);
1534 
1535         mController.updateProvisioningParamsFromIntent(resultIntent);
1536 
1537         assertThat(mController.getParams().keepAccountMigrated).isFalse();
1538     }
1539 
1540     @Test
testUpdateProvisioningParamsFromIntent_managedDeviceModeWithAccountMigratedExtraTrue_accountMigratedIsFalse()1541     public void testUpdateProvisioningParamsFromIntent_managedDeviceModeWithAccountMigratedExtraTrue_accountMigratedIsFalse() {
1542         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1543                 .putExtra(EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION, true);
1544         final ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1545                 .build();
1546         initiateProvisioning(params);
1547 
1548         mController.updateProvisioningParamsFromIntent(resultIntent);
1549 
1550         assertThat(mController.getParams().keepAccountMigrated).isFalse();
1551     }
1552 
1553     @Test
testUpdateProvisioningParamsFromIntent_managedProfileModeWithLeaveSystemAppsEnabledTrue_setsParamToTrue()1554     public void testUpdateProvisioningParamsFromIntent_managedProfileModeWithLeaveSystemAppsEnabledTrue_setsParamToTrue() {
1555         Intent resultIntent = createResultIntentWithManagedProfile()
1556                 .putExtra(EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, true);
1557         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1558                 .build();
1559         initiateProvisioning(params);
1560 
1561         mController.updateProvisioningParamsFromIntent(resultIntent);
1562 
1563         assertThat(mController.getParams().leaveAllSystemAppsEnabled).isTrue();
1564     }
1565 
1566     @Test
testUpdateProvisioningParamsFromIntent_managedProfileModeWithLeaveSystemAppsEnabledFalse_setsParamToFalse()1567     public void testUpdateProvisioningParamsFromIntent_managedProfileModeWithLeaveSystemAppsEnabledFalse_setsParamToFalse() {
1568         Intent resultIntent = createResultIntentWithManagedProfile()
1569                 .putExtra(EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, false);
1570         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1571                 .build();
1572         initiateProvisioning(params);
1573 
1574         mController.updateProvisioningParamsFromIntent(resultIntent);
1575 
1576         assertThat(mController.getParams().leaveAllSystemAppsEnabled).isFalse();
1577     }
1578 
1579     @Test
testUpdateProvisioningParamsFromIntent_managedProfileMode_leaveSystemAppsEnabledIsFalse()1580     public void testUpdateProvisioningParamsFromIntent_managedProfileMode_leaveSystemAppsEnabledIsFalse() {
1581         Intent resultIntent = createResultIntentWithManagedProfile();
1582         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1583                 .build();
1584         initiateProvisioning(params);
1585 
1586         mController.updateProvisioningParamsFromIntent(resultIntent);
1587 
1588         assertThat(mController.getParams().leaveAllSystemAppsEnabled).isFalse();
1589     }
1590 
1591     @Test
testUpdateProvisioningParamsFromIntent_managedDeviceModeWithLeaveSystemAppsEnabledTrue_paramIsFalse()1592     public void testUpdateProvisioningParamsFromIntent_managedDeviceModeWithLeaveSystemAppsEnabledTrue_paramIsFalse() {
1593         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1594                 .putExtra(EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, true);
1595         final ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1596                 .build();
1597         initiateProvisioning(params);
1598 
1599         mController.updateProvisioningParamsFromIntent(resultIntent);
1600 
1601         assertThat(mController.getParams().leaveAllSystemAppsEnabled).isFalse();
1602     }
1603 
1604     @Test
testUpdateProvisioningParamsFromIntent_adminBundlePassed_setsParam()1605     public void testUpdateProvisioningParamsFromIntent_adminBundlePassed_setsParam() {
1606         PersistableBundle testAdminExtrasBundle = new PersistableBundle();
1607         testAdminExtrasBundle.putInt("key1", 2);
1608         testAdminExtrasBundle.putString("key2", "value2");
1609         Intent resultIntent = createResultIntentWithManagedProfile()
1610                 .putExtra(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE, testAdminExtrasBundle);
1611         final ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1612                 .build();
1613         initiateProvisioning(params);
1614 
1615         mController.updateProvisioningParamsFromIntent(resultIntent);
1616 
1617         assertThat(mController.getParams().adminExtrasBundle).isEqualTo(testAdminExtrasBundle);
1618     }
1619 
1620     @Test
testUpdateProvisioningParamsFromIntent_adminBundlePassedWithPreexistingAdminBundle_appendsValues()1621     public void testUpdateProvisioningParamsFromIntent_adminBundlePassedWithPreexistingAdminBundle_appendsValues() {
1622         PersistableBundle resultingAdminBundle = new PersistableBundle();
1623         resultingAdminBundle.putInt("key1", 2);
1624         resultingAdminBundle.putInt("someKey", 124);
1625         PersistableBundle existingAdminBundle = new PersistableBundle();
1626         existingAdminBundle.putInt("key2", 3);
1627         existingAdminBundle.putInt("someKey", 123);
1628         PersistableBundle expectedResult = new PersistableBundle();
1629         expectedResult.putInt("key1", 2);
1630         expectedResult.putInt("key2", 3);
1631         expectedResult.putInt("someKey", 124);
1632         Intent resultIntent = createResultIntentWithManagedProfile()
1633                 .putExtra(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE, resultingAdminBundle);
1634         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1635                 .setAdminExtrasBundle(existingAdminBundle)
1636                 .setKeepAccountMigrated(false)
1637                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1638                         PROVISIONING_MODE_MANAGED_PROFILE
1639                 )))
1640                 .build();
1641         initiateProvisioning(params);
1642 
1643         mController.updateProvisioningParamsFromIntent(resultIntent);
1644 
1645         assertThat(mController.getParams().adminExtrasBundle.toString())
1646                 .isEqualTo(expectedResult.toString());
1647     }
1648 
1649     @Test
testUpdateProvisioningParamsFromIntent_noAdminBundleResult_existingAdminBundleRetained()1650     public void testUpdateProvisioningParamsFromIntent_noAdminBundleResult_existingAdminBundleRetained() {
1651         PersistableBundle existingAdminBundle = new PersistableBundle();
1652         existingAdminBundle.putInt("key2", 3);
1653         existingAdminBundle.putInt("someKey", 123);
1654         Intent resultIntent = createResultIntentWithManagedProfile();
1655         final ProvisioningParams params = createProvisioningParamsBuilderForInitiateProvisioning()
1656                 .setAdminExtrasBundle(existingAdminBundle)
1657                 .setKeepAccountMigrated(false)
1658                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
1659                         PROVISIONING_MODE_MANAGED_PROFILE
1660                 )))
1661                 .build();
1662         initiateProvisioning(params);
1663 
1664         mController.updateProvisioningParamsFromIntent(resultIntent);
1665 
1666         assertThat(mController.getParams().adminExtrasBundle.toString())
1667                 .isEqualTo(existingAdminBundle.toString());
1668     }
1669 
1670     @Test
testUpdateProvisioningParamsFromIntent_validDisclaimersWithWorkProfile_works()1671     public void testUpdateProvisioningParamsFromIntent_validDisclaimersWithWorkProfile_works() {
1672         Intent resultIntent = createResultIntentWithManagedProfile()
1673                 .putExtra(EXTRA_PROVISIONING_DISCLAIMERS, DISCLAIMERS_EXTRA);
1674         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1675                 .build();
1676         initiateProvisioning(params);
1677 
1678         mController.updateProvisioningParamsFromIntent(resultIntent);
1679 
1680         assertThat(mController.getParams().disclaimersParam).isEqualTo(DISCLAIMERS_PARAM);
1681     }
1682 
1683     @Test
testUpdateProvisioningParamsFromIntent_validDisclaimersWithDeviceOwner_works()1684     public void testUpdateProvisioningParamsFromIntent_validDisclaimersWithDeviceOwner_works() {
1685         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1686                 .putExtra(EXTRA_PROVISIONING_DISCLAIMERS, DISCLAIMERS_EXTRA);
1687         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1688                 .build();
1689         initiateProvisioning(params);
1690 
1691         mController.updateProvisioningParamsFromIntent(resultIntent);
1692 
1693         assertThat(mController.getParams().disclaimersParam).isEqualTo(DISCLAIMERS_PARAM);
1694     }
1695 
1696     @Test
testUpdateProvisioningParamsFromIntent_noDisclaimersSet_isNull()1697     public void testUpdateProvisioningParamsFromIntent_noDisclaimersSet_isNull() {
1698         Intent resultIntent = createResultIntentWithManagedProfile();
1699         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1700                 .build();
1701         initiateProvisioning(params);
1702 
1703         mController.updateProvisioningParamsFromIntent(resultIntent);
1704 
1705         assertThat(mController.getParams().disclaimersParam).isNull();
1706     }
1707 
1708     @Test
testUpdateProvisioningParamsFromIntent_withPreExistingDisclaimers_replaced()1709     public void testUpdateProvisioningParamsFromIntent_withPreExistingDisclaimers_replaced() {
1710         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1711                 .putExtra(EXTRA_PROVISIONING_DISCLAIMERS, DISCLAIMERS_EXTRA);
1712         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1713                 .setDisclaimersParam(OTHER_DISCLAIMERS_PARAM)
1714                 .build();
1715         initiateProvisioning(params);
1716 
1717         mController.updateProvisioningParamsFromIntent(resultIntent);
1718 
1719         assertThat(mController.getParams().disclaimersParam).isEqualTo(DISCLAIMERS_PARAM);
1720     }
1721 
1722     @Test
testUpdateProvisioningParamsFromIntent_validLocaleWithWorkProfile_ignored()1723     public void testUpdateProvisioningParamsFromIntent_validLocaleWithWorkProfile_ignored() {
1724         Intent resultIntent = createResultIntentWithManagedProfile()
1725                 .putExtra(EXTRA_PROVISIONING_LOCALE, LOCALE_EXTRA);
1726         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1727                 .build();
1728         initiateProvisioning(params);
1729 
1730         mController.updateProvisioningParamsFromIntent(resultIntent);
1731 
1732         assertThat(mController.getParams().locale).isNull();
1733     }
1734 
1735     @Test
testUpdateProvisioningParamsFromIntent_validLocaleWithDeviceOwner_works()1736     public void testUpdateProvisioningParamsFromIntent_validLocaleWithDeviceOwner_works() {
1737         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1738                 .putExtra(EXTRA_PROVISIONING_LOCALE, LOCALE_EXTRA);
1739         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1740                 .build();
1741         initiateProvisioning(params);
1742 
1743         mController.updateProvisioningParamsFromIntent(resultIntent);
1744 
1745         assertThat(mController.getParams().locale).isEqualTo(LOCALE);
1746     }
1747 
1748     @Test
testUpdateProvisioningParamsFromIntent_noLocaleSet_isNull()1749     public void testUpdateProvisioningParamsFromIntent_noLocaleSet_isNull() {
1750         Intent resultIntent = createResultIntentWithManagedProfile();
1751         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1752                 .build();
1753         initiateProvisioning(params);
1754 
1755         mController.updateProvisioningParamsFromIntent(resultIntent);
1756 
1757         assertThat(mController.getParams().locale).isNull();
1758     }
1759 
1760     @Test
testUpdateProvisioningParamsFromIntent_withPreExistingLocale_replaced()1761     public void testUpdateProvisioningParamsFromIntent_withPreExistingLocale_replaced() {
1762         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1763                 .putExtra(EXTRA_PROVISIONING_LOCALE, LOCALE_EXTRA);
1764         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1765                 .setLocale(OTHER_LOCALE)
1766                 .build();
1767         initiateProvisioning(params);
1768 
1769         mController.updateProvisioningParamsFromIntent(resultIntent);
1770 
1771         assertThat(mController.getParams().locale).isEqualTo(LOCALE);
1772     }
1773 
1774     @Test
testUpdateProvisioningParamsFromIntent_invalidLocale_ignored()1775     public void testUpdateProvisioningParamsFromIntent_invalidLocale_ignored() {
1776         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1777                 .putExtra(EXTRA_PROVISIONING_LOCALE, INVALID_LOCALE_EXTRA);
1778         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1779                 .build();
1780         initiateProvisioning(params);
1781 
1782         mController.updateProvisioningParamsFromIntent(resultIntent);
1783 
1784         assertThat(mController.getParams().locale).isNull();
1785     }
1786 
1787     @Test
testUpdateProvisioningParamsFromIntent_localTimeWithWorkProfile_ignored()1788     public void testUpdateProvisioningParamsFromIntent_localTimeWithWorkProfile_ignored() {
1789         Intent resultIntent = createResultIntentWithManagedProfile()
1790                 .putExtra(EXTRA_PROVISIONING_LOCAL_TIME, LOCAL_TIME_EXTRA);
1791         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1792                 .build();
1793         initiateProvisioning(params);
1794 
1795         mController.updateProvisioningParamsFromIntent(resultIntent);
1796 
1797         assertThat(mController.getParams().localTime).isEqualTo(DEFAULT_LOCAL_TIME);
1798     }
1799 
1800     @Test
testUpdateProvisioningParamsFromIntent_localTimeWithDeviceOwner_works()1801     public void testUpdateProvisioningParamsFromIntent_localTimeWithDeviceOwner_works() {
1802         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1803                 .putExtra(EXTRA_PROVISIONING_LOCAL_TIME, LOCAL_TIME_EXTRA);
1804         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1805                 .build();
1806         initiateProvisioning(params);
1807 
1808         mController.updateProvisioningParamsFromIntent(resultIntent);
1809 
1810         assertThat(mController.getParams().localTime).isEqualTo(LOCAL_TIME_EXTRA);
1811     }
1812 
1813     @Test
testUpdateProvisioningParamsFromIntent_noLocalTimeSet_isDefaultLocalTime()1814     public void testUpdateProvisioningParamsFromIntent_noLocalTimeSet_isDefaultLocalTime() {
1815         Intent resultIntent = createResultIntentWithManagedProfile();
1816         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1817                 .build();
1818         initiateProvisioning(params);
1819 
1820         mController.updateProvisioningParamsFromIntent(resultIntent);
1821 
1822         assertThat(mController.getParams().localTime).isEqualTo(DEFAULT_LOCAL_TIME);
1823     }
1824 
1825     @Test
testUpdateProvisioningParamsFromIntent_withPreExistingLocalTime_replaced()1826     public void testUpdateProvisioningParamsFromIntent_withPreExistingLocalTime_replaced() {
1827         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1828                 .putExtra(EXTRA_PROVISIONING_LOCAL_TIME, LOCAL_TIME_EXTRA);
1829         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1830                 .setLocalTime(OTHER_LOCAL_TIME)
1831                 .build();
1832         initiateProvisioning(params);
1833 
1834         mController.updateProvisioningParamsFromIntent(resultIntent);
1835 
1836         assertThat(mController.getParams().localTime).isEqualTo(LOCAL_TIME_EXTRA);
1837     }
1838 
1839     @Test
testUpdateProvisioningParamsFromIntent_timeZoneWithWorkProfile_ignored()1840     public void testUpdateProvisioningParamsFromIntent_timeZoneWithWorkProfile_ignored() {
1841         Intent resultIntent = createResultIntentWithManagedProfile()
1842                 .putExtra(EXTRA_PROVISIONING_TIME_ZONE, TIME_ZONE_EXTRA);
1843         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1844                 .build();
1845         initiateProvisioning(params);
1846 
1847         mController.updateProvisioningParamsFromIntent(resultIntent);
1848 
1849         assertThat(mController.getParams().timeZone).isNull();
1850     }
1851 
1852     @Test
testUpdateProvisioningParamsFromIntent_timeZoneWithDeviceOwner_works()1853     public void testUpdateProvisioningParamsFromIntent_timeZoneWithDeviceOwner_works() {
1854         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1855                 .putExtra(EXTRA_PROVISIONING_TIME_ZONE, TIME_ZONE_EXTRA);
1856         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1857                 .build();
1858         initiateProvisioning(params);
1859 
1860         mController.updateProvisioningParamsFromIntent(resultIntent);
1861 
1862         assertThat(mController.getParams().timeZone).isEqualTo(TIME_ZONE_EXTRA);
1863     }
1864 
1865     @Test
testUpdateProvisioningParamsFromIntent_noTimeZoneSet_isNull()1866     public void testUpdateProvisioningParamsFromIntent_noTimeZoneSet_isNull() {
1867         Intent resultIntent = createResultIntentWithManagedProfile();
1868         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1869                 .build();
1870         initiateProvisioning(params);
1871 
1872         mController.updateProvisioningParamsFromIntent(resultIntent);
1873 
1874         assertThat(mController.getParams().timeZone).isNull();
1875     }
1876 
1877     @Test
testUpdateProvisioningParamsFromIntent_withPreExistingTimeZone_replaced()1878     public void testUpdateProvisioningParamsFromIntent_withPreExistingTimeZone_replaced() {
1879         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1880                 .putExtra(EXTRA_PROVISIONING_TIME_ZONE, TIME_ZONE_EXTRA);
1881         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1882                 .setTimeZone(OTHER_TIME_ZONE)
1883                 .build();
1884         initiateProvisioning(params);
1885 
1886         mController.updateProvisioningParamsFromIntent(resultIntent);
1887 
1888         assertThat(mController.getParams().timeZone).isEqualTo(TIME_ZONE_EXTRA);
1889     }
1890 
1891     @Test
testUpdateProvisioningParamsFromIntent_skipEncryptionWithWorkProfile_works()1892     public void testUpdateProvisioningParamsFromIntent_skipEncryptionWithWorkProfile_works() {
1893         Intent resultIntent = createResultIntentWithManagedProfile()
1894                 .putExtra(EXTRA_PROVISIONING_SKIP_ENCRYPTION, /* value= */ true);
1895         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1896                 .build();
1897         initiateProvisioning(params);
1898 
1899         mController.updateProvisioningParamsFromIntent(resultIntent);
1900 
1901         assertThat(mController.getParams().skipEncryption).isTrue();
1902     }
1903 
1904     @Test
testUpdateProvisioningParamsFromIntent_skipEncryptionWithDeviceOwner_works()1905     public void testUpdateProvisioningParamsFromIntent_skipEncryptionWithDeviceOwner_works() {
1906         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1907                 .putExtra(EXTRA_PROVISIONING_SKIP_ENCRYPTION, /* value= */ true);
1908         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1909                 .build();
1910         initiateProvisioning(params);
1911 
1912         mController.updateProvisioningParamsFromIntent(resultIntent);
1913 
1914         assertThat(mController.getParams().skipEncryption).isTrue();
1915     }
1916 
1917     @Test
testUpdateProvisioningParamsFromIntent_noSkipEncryptionSet_isFalse()1918     public void testUpdateProvisioningParamsFromIntent_noSkipEncryptionSet_isFalse() {
1919         Intent resultIntent = createResultIntentWithManagedProfile();
1920         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1921                 .build();
1922         initiateProvisioning(params);
1923 
1924         mController.updateProvisioningParamsFromIntent(resultIntent);
1925 
1926         assertThat(mController.getParams().skipEncryption).isFalse();
1927     }
1928 
1929     @Test
testUpdateProvisioningParamsFromIntent_withPreExistingSkipEncryption_replaced()1930     public void testUpdateProvisioningParamsFromIntent_withPreExistingSkipEncryption_replaced() {
1931         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1932                 .putExtra(EXTRA_PROVISIONING_SKIP_ENCRYPTION, true);
1933         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1934                 .setSkipEncryption(false)
1935                 .build();
1936         initiateProvisioning(params);
1937 
1938         mController.updateProvisioningParamsFromIntent(resultIntent);
1939 
1940         assertThat(mController.getParams().skipEncryption).isTrue();
1941     }
1942 
1943     @Test
testUpdateProvisioningParamsFromIntent_deviceOwnerPermissionGrantOptOutWithWorkProfile_ignored()1944     public void testUpdateProvisioningParamsFromIntent_deviceOwnerPermissionGrantOptOutWithWorkProfile_ignored() {
1945         Intent resultIntent = createResultIntentWithManagedProfile()
1946                 .putExtra(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT, /* value= */ true);
1947         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1948                 .build();
1949         initiateProvisioning(params);
1950 
1951         mController.updateProvisioningParamsFromIntent(resultIntent);
1952 
1953         assertThat(mController.getParams().deviceOwnerPermissionGrantOptOut).isFalse();
1954     }
1955 
1956     @Test
testUpdateProvisioningParamsFromIntent_deviceOwnerPermissionGrantOptOutWithDeviceOwner_works()1957     public void testUpdateProvisioningParamsFromIntent_deviceOwnerPermissionGrantOptOutWithDeviceOwner_works() {
1958         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1959                 .putExtra(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT, /* value= */ true);
1960         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1961                 .build();
1962         initiateProvisioning(params);
1963 
1964         mController.updateProvisioningParamsFromIntent(resultIntent);
1965 
1966         assertThat(mController.getParams().deviceOwnerPermissionGrantOptOut).isTrue();
1967     }
1968 
1969     @Test
testUpdateProvisioningParamsFromIntent_noDeviceOwnerPermissionGrantOptOutSet_isFalse()1970     public void testUpdateProvisioningParamsFromIntent_noDeviceOwnerPermissionGrantOptOutSet_isFalse() {
1971         Intent resultIntent = createResultIntentWithManagedProfile();
1972         ProvisioningParams params = createProvisioningParamsBuilderForManagedProfile()
1973                 .build();
1974         initiateProvisioning(params);
1975 
1976         mController.updateProvisioningParamsFromIntent(resultIntent);
1977 
1978         assertThat(mController.getParams().deviceOwnerPermissionGrantOptOut).isFalse();
1979     }
1980 
1981     @Test
testUpdateProvisioningParamsFromIntent_withPreExistingDeviceOwnerPermissionGrantOptOut_replaced()1982     public void testUpdateProvisioningParamsFromIntent_withPreExistingDeviceOwnerPermissionGrantOptOut_replaced() {
1983         Intent resultIntent = createResultIntentWithFullyManagedDevice()
1984                 .putExtra(EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT, /* value= */ true);
1985         ProvisioningParams params = createProvisioningParamsBuilderForFullyManagedDevice()
1986                 .setDeviceOwnerPermissionGrantOptOut(false)
1987                 .build();
1988         initiateProvisioning(params);
1989 
1990         mController.updateProvisioningParamsFromIntent(resultIntent);
1991 
1992         assertThat(mController.getParams().deviceOwnerPermissionGrantOptOut).isTrue();
1993     }
1994 
1995     @Test
testInitiateProvisioning_withActionProvisionManagedDevice_failsSilently()1996     public void testInitiateProvisioning_withActionProvisionManagedDevice_failsSilently()
1997             throws Exception {
1998         prepareMocksForDoIntent(/* skipEncryption= */ false);
1999 
2000         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
2001             mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE);
2002         });
2003 
2004         verify(mUi, never()).initiateUi(any());
2005         verify(mUi).abortProvisioning();
2006         verifyNoMoreInteractions(mUi);
2007     }
createDisclaimersExtra()2008     private static Parcelable[] createDisclaimersExtra() {
2009         Bundle disclaimer = new Bundle();
2010         disclaimer.putString(
2011                 EXTRA_PROVISIONING_DISCLAIMER_HEADER, DISCLAIMER_HEADER);
2012         disclaimer.putParcelable(EXTRA_PROVISIONING_DISCLAIMER_CONTENT, DISCLAIMER_CONTENT_URI);
2013         return new Parcelable[]{ disclaimer };
2014     }
2015 
createProvisioningParamsBuilderForInitiateProvisioning()2016     private ProvisioningParams.Builder createProvisioningParamsBuilderForInitiateProvisioning() {
2017         return createProvisioningParamsBuilder()
2018                 .setDeviceAdminDownloadInfo(PACKAGE_DOWNLOAD_INFO);
2019     }
2020 
prepareMocksForManagedProfileIntent(ProvisioningParams params)2021     private void prepareMocksForManagedProfileIntent(ProvisioningParams params) throws Exception {
2022         final String action = ACTION_PROVISION_MANAGED_PROFILE;
2023         when(mIntent.getAction()).thenReturn(action);
2024         when(mUtils.findDeviceAdmin(TEST_MDM_PACKAGE, null, mContext, UserHandle.myUserId()))
2025                 .thenReturn(TEST_MDM_COMPONENT_NAME);
2026         when(mSettingsFacade.isDeviceProvisioned(mContext)).thenReturn(true);
2027         when(mDevicePolicyManager.checkProvisioningPrecondition(action, TEST_MDM_PACKAGE))
2028                 .thenReturn(STATUS_OK);
2029         when(mMessageParser.parse(mIntent)).thenReturn(params);
2030     }
2031 
prepareMocksForManagedProfileIntent(boolean skipEncryption)2032     private void prepareMocksForManagedProfileIntent(boolean skipEncryption) throws Exception {
2033         final String action = ACTION_PROVISION_MANAGED_PROFILE;
2034         when(mIntent.getAction()).thenReturn(action);
2035         when(mUtils.findDeviceAdmin(TEST_MDM_PACKAGE, null, mContext, UserHandle.myUserId()))
2036                 .thenReturn(TEST_MDM_COMPONENT_NAME);
2037         when(mSettingsFacade.isDeviceProvisioned(mContext)).thenReturn(true);
2038         when(mDevicePolicyManager.checkProvisioningPrecondition(action, TEST_MDM_PACKAGE))
2039                 .thenReturn(STATUS_OK);
2040         when(mMessageParser.parse(mIntent)).thenReturn(
2041                 createParams(false, skipEncryption, null, action, TEST_MDM_PACKAGE));
2042     }
2043 
prepareMocksForFinancedDeviceIntent()2044     private void prepareMocksForFinancedDeviceIntent() throws Exception {
2045         final String action = ACTION_PROVISION_FINANCED_DEVICE;
2046         when(mIntent.getAction()).thenReturn(action);
2047         when(mIntent.getComponent()).thenReturn(ComponentName.createRelative(MP_PACKAGE_NAME,
2048                 ".PreProvisioningActivityViaTrustedApp"));
2049         when(mUtils.findDeviceAdmin(TEST_MDM_PACKAGE, null, mContext, UserHandle.myUserId()))
2050                 .thenReturn(TEST_MDM_COMPONENT_NAME);
2051         when(mDevicePolicyManager.checkProvisioningPrecondition(action, TEST_MDM_PACKAGE))
2052                 .thenReturn(STATUS_OK);
2053         when(mMessageParser.parse(mIntent)).thenReturn(
2054                 createParams(false, false, null, action, TEST_MDM_PACKAGE));
2055     }
2056 
prepareMocksForTrustedSourceIntent(ProvisioningParams params)2057     private void prepareMocksForTrustedSourceIntent(ProvisioningParams params) throws Exception {
2058         when(mIntent.getAction())
2059                 .thenReturn(ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE);
2060         when(mIntent.getComponent()).thenReturn(ComponentName.createRelative(MP_PACKAGE_NAME,
2061                 ".PreProvisioningActivityViaTrustedApp"));
2062         when(mDevicePolicyManager.checkProvisioningPrecondition(anyString(), eq(TEST_MDM_PACKAGE)))
2063                 .thenReturn(STATUS_OK);
2064         when(mMessageParser.parse(mIntent)).thenReturn(params);
2065     }
2066 
prepareMocksForDoIntent(boolean skipEncryption)2067     private void prepareMocksForDoIntent(boolean skipEncryption) throws Exception {
2068         final String action = ACTION_PROVISION_MANAGED_DEVICE;
2069         when(mIntent.getAction()).thenReturn(action);
2070         when(mDevicePolicyManager.checkProvisioningPrecondition(action, TEST_MDM_PACKAGE))
2071                 .thenReturn(STATUS_OK);
2072         when(mMessageParser.parse(mIntent)).thenReturn(
2073                 createParams(false, skipEncryption, TEST_WIFI_SSID, action, TEST_MDM_PACKAGE));
2074     }
2075 
prepareMocksForAfterEncryption(String action, boolean startedByTrustedSource)2076     private void prepareMocksForAfterEncryption(String action, boolean startedByTrustedSource)
2077             throws Exception {
2078         when(mIntent.getAction()).thenReturn(ACTION_RESUME_PROVISIONING);
2079         when(mIntent.getComponent()).thenReturn(ComponentName.createRelative(MP_PACKAGE_NAME,
2080                 ".PreProvisioningActivityAfterEncryption"));
2081         when(mDevicePolicyManager.checkProvisioningPrecondition(action, TEST_MDM_PACKAGE))
2082                 .thenReturn(STATUS_OK);
2083         when(mMessageParser.parse(mIntent)).thenReturn(
2084                 createParams(
2085                         startedByTrustedSource, false, TEST_WIFI_SSID, action, TEST_MDM_PACKAGE));
2086     }
2087 
createParamsBuilder( boolean startedByTrustedSource, boolean skipEncryption, String wifiSsid, String action, String packageName)2088     private ProvisioningParams.Builder createParamsBuilder(
2089             boolean startedByTrustedSource, boolean skipEncryption,
2090             String wifiSsid, String action, String packageName) {
2091         ProvisioningParams.Builder builder = ProvisioningParams.Builder.builder()
2092                 .setStartedByTrustedSource(startedByTrustedSource)
2093                 .setSkipEncryption(skipEncryption)
2094                 .setProvisioningAction(action)
2095                 .setDeviceAdminPackageName(packageName);
2096         if (!TextUtils.isEmpty(wifiSsid)) {
2097             builder.setWifiInfo(WifiInfo.Builder.builder().setSsid(wifiSsid).build());
2098         }
2099         return builder;
2100     }
2101 
createParams(boolean startedByTrustedSource, boolean skipEncryption, String wifiSsid, String action, String packageName)2102     private ProvisioningParams createParams(boolean startedByTrustedSource, boolean skipEncryption,
2103             String wifiSsid, String action, String packageName) {
2104         return mParams = createParamsBuilder(
2105                 startedByTrustedSource, skipEncryption, wifiSsid, action, packageName).build();
2106     }
2107 
verifyInitiateProfileOwnerUi()2108     private void verifyInitiateProfileOwnerUi() {
2109         verify(mUi).initiateUi(any());
2110     }
2111 
verifyInitiateDeviceOwnerUi()2112     private void verifyInitiateDeviceOwnerUi() {
2113         verify(mUi).initiateUi(any());
2114     }
2115 
createProvisioningParamsBuilder()2116     private ProvisioningParams.Builder createProvisioningParamsBuilder() {
2117         return ProvisioningParams.Builder.builder()
2118                 .setProvisioningAction(ACTION_PROVISION_MANAGED_DEVICE)
2119                 .setStartedByTrustedSource(true)
2120                 .setDeviceAdminComponentName(TEST_MDM_COMPONENT_NAME);
2121     }
2122 
initiateProvisioning(ProvisioningParams params)2123     private void initiateProvisioning(ProvisioningParams params) {
2124         try {
2125             when(mMessageParser.parse(any(Intent.class))).thenReturn(params);
2126         } catch (IllegalProvisioningArgumentException e) {
2127             // will never happen
2128         }
2129         InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
2130                 mController.initiateProvisioning(mIntent, TEST_MDM_PACKAGE));
2131     }
2132 
createProvisioningParamsBuilderForFullyManagedDevice()2133     private ProvisioningParams.Builder createProvisioningParamsBuilderForFullyManagedDevice() {
2134         return createProvisioningParamsBuilderForInitiateProvisioning()
2135                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
2136                         PROVISIONING_MODE_FULLY_MANAGED_DEVICE
2137                 )));
2138     }
2139 
createProvisioningParamsBuilderForManagedProfile()2140     private ProvisioningParams.Builder createProvisioningParamsBuilderForManagedProfile() {
2141         return createProvisioningParamsBuilderForInitiateProvisioning()
2142                 .setAllowedProvisioningModes(new ArrayList<>(List.of(
2143                         PROVISIONING_MODE_MANAGED_PROFILE
2144                 )));
2145     }
2146 
createResultIntentWithManagedProfile()2147     private Intent createResultIntentWithManagedProfile() {
2148         return new Intent()
2149                 .putExtra(EXTRA_PROVISIONING_MODE, PROVISIONING_MODE_MANAGED_PROFILE);
2150     }
2151 
createResultIntentWithFullyManagedDevice()2152     private Intent createResultIntentWithFullyManagedDevice() {
2153         return new Intent()
2154                 .putExtra(EXTRA_PROVISIONING_MODE, PROVISIONING_MODE_FULLY_MANAGED_DEVICE);
2155     }
2156 
createControllerWithRoleHolderUpdaterInstalled()2157     private PreProvisioningActivityController createControllerWithRoleHolderUpdaterInstalled() {
2158         return createControllerWithRoleHolderHelpers(
2159                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT,
2160                 ROLE_HOLDER_UPDATER_HELPER);
2161     }
2162 
2163     private PreProvisioningActivityController
createControllerWithRoleHolderValidAndInstalledWithUpdater( DeviceManagementRoleHolderUpdaterHelper updaterHelper)2164     createControllerWithRoleHolderValidAndInstalledWithUpdater(
2165             DeviceManagementRoleHolderUpdaterHelper updaterHelper) {
2166         return createControllerWithRoleHolderHelpers(
2167                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER,
2168                 updaterHelper);
2169     }
2170 
createControllerWithRoleHolderUpdaterNotPresent()2171     private PreProvisioningActivityController createControllerWithRoleHolderUpdaterNotPresent() {
2172         return createControllerWithRoleHolderHelpers(
2173                 DEVICE_MANAGEMENT_ROLE_HOLDER_HELPER_NOT_PRESENT,
2174                 ROLE_HOLDER_UPDATER_HELPER_UPDATER_NOT_INSTALLED);
2175     }
2176 
createRoleHolderStateBundle()2177     private static PersistableBundle createRoleHolderStateBundle() {
2178         PersistableBundle result = new PersistableBundle();
2179         result.putString("key1", "value1");
2180         result.putInt("key2", 2);
2181         result.putBoolean("key3", true);
2182         return result;
2183     }
2184 
createFeatureFlagChecker()2185     private static FeatureFlagChecker createFeatureFlagChecker() {
2186         return () -> sDelegateProvisioningToRoleHolderEnabled;
2187     }
2188 
enableRoleHolderDelegation()2189     private void enableRoleHolderDelegation() {
2190         sDelegateProvisioningToRoleHolderEnabled = true;
2191     }
2192 
disableRoleHolderDelegation()2193     private void disableRoleHolderDelegation() {
2194         sDelegateProvisioningToRoleHolderEnabled = false;
2195     }
2196 
createSuccessfulUpdateAdditionalExtras()2197     private static Bundle createSuccessfulUpdateAdditionalExtras() {
2198         Bundle bundle = new Bundle();
2199         bundle.putInt(EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE, RESULT_OK);
2200         return bundle;
2201     }
2202 }
2203