WifiConfigManagerTest.java revision c8d71776a203bd1a515caa2e06570eab34b9c22e
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
17package com.android.server.wifi;
18
19import static org.junit.Assert.*;
20import static org.mockito.Mockito.*;
21
22import android.app.admin.DeviceAdminInfo;
23import android.app.admin.DevicePolicyManagerInternal;
24import android.app.test.MockAnswerUtil.AnswerWithArguments;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageManager;
29import android.content.pm.UserInfo;
30import android.net.IpConfiguration;
31import android.net.wifi.ScanResult;
32import android.net.wifi.WifiConfiguration;
33import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
34import android.net.wifi.WifiEnterpriseConfig;
35import android.net.wifi.WifiManager;
36import android.net.wifi.WifiScanner;
37import android.net.wifi.WifiSsid;
38import android.os.UserHandle;
39import android.os.UserManager;
40import android.telephony.TelephonyManager;
41import android.test.suitebuilder.annotation.SmallTest;
42import android.text.TextUtils;
43import android.util.Pair;
44
45import com.android.internal.R;
46import com.android.server.wifi.WifiConfigStoreLegacy.WifiConfigStoreDataLegacy;
47import com.android.server.wifi.util.WifiPermissionsWrapper;
48
49import org.junit.After;
50import org.junit.Before;
51import org.junit.Test;
52import org.mockito.ArgumentCaptor;
53import org.mockito.InOrder;
54import org.mockito.Mock;
55import org.mockito.MockitoAnnotations;
56
57import java.io.FileDescriptor;
58import java.io.PrintWriter;
59import java.io.StringWriter;
60import java.util.ArrayList;
61import java.util.Arrays;
62import java.util.HashSet;
63import java.util.List;
64import java.util.Random;
65import java.util.Set;
66
67/**
68 * Unit tests for {@link com.android.server.wifi.WifiConfigManager}.
69 */
70@SmallTest
71public class WifiConfigManagerTest {
72
73    private static final String TEST_BSSID = "0a:08:5c:67:89:00";
74    private static final long TEST_WALLCLOCK_CREATION_TIME_MILLIS = 9845637;
75    private static final long TEST_WALLCLOCK_UPDATE_TIME_MILLIS = 75455637;
76    private static final long TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS = 29457631;
77    private static final int TEST_CREATOR_UID = WifiConfigurationTestUtil.TEST_UID;
78    private static final int TEST_NO_PERM_UID = 7;
79    private static final int TEST_UPDATE_UID = 4;
80    private static final int TEST_SYSUI_UID = 56;
81    private static final int TEST_DEFAULT_USER = UserHandle.USER_SYSTEM;
82    private static final int TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN = 5;
83    private static final Integer[] TEST_FREQ_LIST = {2400, 2450, 5150, 5175, 5650};
84    private static final String TEST_CREATOR_NAME = "com.wificonfigmanager.creator";
85    private static final String TEST_UPDATE_NAME = "com.wificonfigmanager.update";
86    private static final String TEST_NO_PERM_NAME = "com.wificonfigmanager.noperm";
87    private static final String TEST_DEFAULT_GW_MAC_ADDRESS = "0f:67:ad:ef:09:34";
88    private static final String TEST_STATIC_PROXY_HOST_1 = "192.168.48.1";
89    private static final int    TEST_STATIC_PROXY_PORT_1 = 8000;
90    private static final String TEST_STATIC_PROXY_EXCLUSION_LIST_1 = "";
91    private static final String TEST_PAC_PROXY_LOCATION_1 = "http://bleh";
92    private static final String TEST_STATIC_PROXY_HOST_2 = "192.168.1.1";
93    private static final int    TEST_STATIC_PROXY_PORT_2 = 3000;
94    private static final String TEST_STATIC_PROXY_EXCLUSION_LIST_2 = "";
95    private static final String TEST_PAC_PROXY_LOCATION_2 = "http://blah";
96
97    @Mock private Context mContext;
98    @Mock private FrameworkFacade mFrameworkFacade;
99    @Mock private Clock mClock;
100    @Mock private UserManager mUserManager;
101    @Mock private TelephonyManager mTelephonyManager;
102    @Mock private WifiKeyStore mWifiKeyStore;
103    @Mock private WifiConfigStore mWifiConfigStore;
104    @Mock private WifiConfigStoreLegacy mWifiConfigStoreLegacy;
105    @Mock private PackageManager mPackageManager;
106    @Mock private DevicePolicyManagerInternal mDevicePolicyManagerInternal;
107    @Mock private WifiPermissionsWrapper mWifiPermissionsWrapper;
108    @Mock private NetworkListStoreData mNetworkListStoreData;
109    @Mock private DeletedEphemeralSsidsStoreData mDeletedEphemeralSsidsStoreData;
110
111    private MockResources mResources;
112    private InOrder mContextConfigStoreMockOrder;
113    private InOrder mNetworkListStoreDataMockOrder;
114    private WifiConfigManager mWifiConfigManager;
115
116    /**
117     * Setup the mocks and an instance of WifiConfigManager before each test.
118     */
119    @Before
120    public void setUp() throws Exception {
121        MockitoAnnotations.initMocks(this);
122
123        // Set up the inorder for verifications. This is needed to verify that the broadcasts,
124        // store writes for network updates followed by network additions are in the expected order.
125        mContextConfigStoreMockOrder = inOrder(mContext, mWifiConfigStore);
126        mNetworkListStoreDataMockOrder = inOrder(mNetworkListStoreData);
127
128        // Set up the package name stuff & permission override.
129        when(mContext.getPackageManager()).thenReturn(mPackageManager);
130        mResources = new MockResources();
131        mResources.setBoolean(
132                R.bool.config_wifi_only_link_same_credential_configurations, true);
133        mResources.setInteger(
134                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
135                TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN);
136        when(mContext.getResources()).thenReturn(mResources);
137
138        // Setup UserManager profiles for the default user.
139        setupUserProfiles(TEST_DEFAULT_USER);
140
141        doAnswer(new AnswerWithArguments() {
142            public String answer(int uid) throws Exception {
143                if (uid == TEST_CREATOR_UID) {
144                    return TEST_CREATOR_NAME;
145                } else if (uid == TEST_UPDATE_UID) {
146                    return TEST_UPDATE_NAME;
147                } else if (uid == TEST_SYSUI_UID) {
148                    return WifiConfigManager.SYSUI_PACKAGE_NAME;
149                } else if (uid == TEST_NO_PERM_UID) {
150                    return TEST_NO_PERM_NAME;
151                }
152                fail("Unexpected UID: " + uid);
153                return "";
154            }
155        }).when(mPackageManager).getNameForUid(anyInt());
156        doAnswer(new AnswerWithArguments() {
157            public int answer(String packageName, int flags, int userId) throws Exception {
158                if (packageName.equals(WifiConfigManager.SYSUI_PACKAGE_NAME)) {
159                    return TEST_SYSUI_UID;
160                } else {
161                    return 0;
162                }
163            }
164        }).when(mPackageManager).getPackageUidAsUser(anyString(), anyInt(), anyInt());
165
166        // Both the UID's in the test have the configuration override permission granted by
167        // default. This maybe modified for particular tests if needed.
168        doAnswer(new AnswerWithArguments() {
169            public int answer(String permName, int uid) throws Exception {
170                if (uid == TEST_CREATOR_UID || uid == TEST_UPDATE_UID || uid == TEST_SYSUI_UID) {
171                    return PackageManager.PERMISSION_GRANTED;
172                }
173                return PackageManager.PERMISSION_DENIED;
174            }
175        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
176
177        when(mWifiKeyStore
178                .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class)))
179                .thenReturn(true);
180
181        when(mWifiConfigStore.areStoresPresent()).thenReturn(true);
182
183        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), anyInt()))
184                .thenReturn(false);
185        when(mWifiPermissionsWrapper.getDevicePolicyManagerInternal())
186                .thenReturn(mDevicePolicyManagerInternal);
187        createWifiConfigManager();
188    }
189
190    /**
191     * Called after each test
192     */
193    @After
194    public void cleanup() {
195        validateMockitoUsage();
196    }
197
198    /**
199     * Verifies that network retrieval via
200     * {@link WifiConfigManager#getConfiguredNetworks()} and
201     * {@link WifiConfigManager#getConfiguredNetworksWithPasswords()} works even if we have not
202     * yet loaded data from store.
203     */
204    @Test
205    public void testGetConfiguredNetworksBeforeLoadFromStore() {
206        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
207        assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
208    }
209
210    /**
211     * Verifies the addition of a single network using
212     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
213     */
214    @Test
215    public void testAddSingleOpenNetwork() {
216        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
217        List<WifiConfiguration> networks = new ArrayList<>();
218        networks.add(openNetwork);
219
220        verifyAddNetworkToWifiConfigManager(openNetwork);
221
222        List<WifiConfiguration> retrievedNetworks =
223                mWifiConfigManager.getConfiguredNetworksWithPasswords();
224        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
225                networks, retrievedNetworks);
226        // Ensure that the newly added network is disabled.
227        assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
228    }
229
230    /**
231     * Verifies the modification of a single network using
232     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
233     */
234    @Test
235    public void testUpdateSingleOpenNetwork() {
236        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
237        List<WifiConfiguration> networks = new ArrayList<>();
238        networks.add(openNetwork);
239
240        verifyAddNetworkToWifiConfigManager(openNetwork);
241
242        // Now change BSSID for the network.
243        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
244        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
245
246        // Now verify that the modification has been effective.
247        List<WifiConfiguration> retrievedNetworks =
248                mWifiConfigManager.getConfiguredNetworksWithPasswords();
249        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
250                networks, retrievedNetworks);
251    }
252
253    /**
254     * Verifies the addition of a single ephemeral network using
255     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
256     * the {@link WifiConfigManager#getSavedNetworks()} does not return this network.
257     */
258    @Test
259    public void testAddSingleEphemeralNetwork() throws Exception {
260        WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
261        ephemeralNetwork.ephemeral = true;
262        List<WifiConfiguration> networks = new ArrayList<>();
263        networks.add(ephemeralNetwork);
264
265        verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
266
267        List<WifiConfiguration> retrievedNetworks =
268                mWifiConfigManager.getConfiguredNetworksWithPasswords();
269        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
270                networks, retrievedNetworks);
271
272        // Ensure that this is not returned in the saved network list.
273        assertTrue(mWifiConfigManager.getSavedNetworks().isEmpty());
274    }
275
276    /**
277     * Verifies the addition of 2 networks (1 normal and 1 ephemeral) using
278     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that
279     * the ephemeral network configuration is not persisted in config store.
280     */
281    @Test
282    public void testAddMultipleNetworksAndEnsureEphemeralNetworkNotPersisted() {
283        WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
284        ephemeralNetwork.ephemeral = true;
285        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
286
287        assertTrue(addNetworkToWifiConfigManager(ephemeralNetwork).isSuccess());
288        assertTrue(addNetworkToWifiConfigManager(openNetwork).isSuccess());
289
290        // The open network addition should trigger a store write.
291        Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData =
292                captureWriteNetworksListStoreData();
293        List<WifiConfiguration> networkList = new ArrayList<>();
294        networkList.addAll(networkListStoreData.first);
295        networkList.addAll(networkListStoreData.second);
296        assertFalse(isNetworkInConfigStoreData(ephemeralNetwork, networkList));
297        assertTrue(isNetworkInConfigStoreData(openNetwork, networkList));
298    }
299
300    /**
301     * Verifies that the modification of a single open network using
302     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with a UID which
303     * has no permission to modify the network fails.
304     */
305    @Test
306    public void testUpdateSingleOpenNetworkFailedDueToPermissionDenied() throws Exception {
307        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
308        List<WifiConfiguration> networks = new ArrayList<>();
309        networks.add(openNetwork);
310
311        verifyAddNetworkToWifiConfigManager(openNetwork);
312
313        // Now change BSSID of the network.
314        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
315
316        // Deny permission for |UPDATE_UID|.
317        doAnswer(new AnswerWithArguments() {
318            public int answer(String permName, int uid) throws Exception {
319                if (uid == TEST_CREATOR_UID) {
320                    return PackageManager.PERMISSION_GRANTED;
321                }
322                return PackageManager.PERMISSION_DENIED;
323            }
324        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
325
326        // Update the same configuration and ensure that the operation failed.
327        NetworkUpdateResult result = updateNetworkToWifiConfigManager(openNetwork);
328        assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
329    }
330
331    /**
332     * Verifies that the modification of a single open network using
333     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with the creator UID
334     * should always succeed.
335     */
336    @Test
337    public void testUpdateSingleOpenNetworkSuccessWithCreatorUID() throws Exception {
338        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
339        List<WifiConfiguration> networks = new ArrayList<>();
340        networks.add(openNetwork);
341
342        verifyAddNetworkToWifiConfigManager(openNetwork);
343
344        // Now change BSSID of the network.
345        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
346
347        // Deny permission for all UIDs.
348        doAnswer(new AnswerWithArguments() {
349            public int answer(String permName, int uid) throws Exception {
350                return PackageManager.PERMISSION_DENIED;
351            }
352        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
353
354        // Update the same configuration using the creator UID.
355        NetworkUpdateResult result =
356                mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID);
357        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
358
359        // Now verify that the modification has been effective.
360        List<WifiConfiguration> retrievedNetworks =
361                mWifiConfigManager.getConfiguredNetworksWithPasswords();
362        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
363                networks, retrievedNetworks);
364    }
365
366    /**
367     * Verifies the addition of a single PSK network using
368     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
369     * {@link WifiConfigManager#getSavedNetworks()} masks the password.
370     */
371    @Test
372    public void testAddSinglePskNetwork() {
373        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
374        List<WifiConfiguration> networks = new ArrayList<>();
375        networks.add(pskNetwork);
376
377        verifyAddNetworkToWifiConfigManager(pskNetwork);
378
379        List<WifiConfiguration> retrievedNetworks =
380                mWifiConfigManager.getConfiguredNetworksWithPasswords();
381        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
382                networks, retrievedNetworks);
383
384        List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks();
385        assertEquals(retrievedSavedNetworks.size(), 1);
386        assertEquals(retrievedSavedNetworks.get(0).configKey(), pskNetwork.configKey());
387        assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0));
388    }
389
390    /**
391     * Verifies the addition of a single WEP network using
392     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
393     * {@link WifiConfigManager#getSavedNetworks()} masks the password.
394     */
395    @Test
396    public void testAddSingleWepNetwork() {
397        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
398        List<WifiConfiguration> networks = new ArrayList<>();
399        networks.add(wepNetwork);
400
401        verifyAddNetworkToWifiConfigManager(wepNetwork);
402
403        List<WifiConfiguration> retrievedNetworks =
404                mWifiConfigManager.getConfiguredNetworksWithPasswords();
405        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
406                networks, retrievedNetworks);
407
408        List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks();
409        assertEquals(retrievedSavedNetworks.size(), 1);
410        assertEquals(retrievedSavedNetworks.get(0).configKey(), wepNetwork.configKey());
411        assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0));
412    }
413
414    /**
415     * Verifies the modification of an IpConfiguration using
416     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
417     */
418    @Test
419    public void testUpdateIpConfiguration() {
420        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
421        List<WifiConfiguration> networks = new ArrayList<>();
422        networks.add(openNetwork);
423
424        verifyAddNetworkToWifiConfigManager(openNetwork);
425
426        // Now change BSSID of the network.
427        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
428
429        // Update the same configuration and ensure that the IP configuration change flags
430        // are not set.
431        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
432
433        // Configure mock DevicePolicyManager to give Profile Owner permission so that we can modify
434        // proxy settings on a configuration
435        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(),
436                eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))).thenReturn(true);
437
438        // Change the IpConfiguration now and ensure that the IP configuration flags are set now.
439        assertAndSetNetworkIpConfiguration(
440                openNetwork,
441                WifiConfigurationTestUtil.createStaticIpConfigurationWithStaticProxy());
442        verifyUpdateNetworkToWifiConfigManagerWithIpChange(openNetwork);
443
444        // Now verify that all the modifications have been effective.
445        List<WifiConfiguration> retrievedNetworks =
446                mWifiConfigManager.getConfiguredNetworksWithPasswords();
447        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
448                networks, retrievedNetworks);
449    }
450
451    /**
452     * Verifies the removal of a single network using
453     * {@link WifiConfigManager#removeNetwork(int)}
454     */
455    @Test
456    public void testRemoveSingleOpenNetwork() {
457        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
458
459        verifyAddNetworkToWifiConfigManager(openNetwork);
460        // Ensure that configured network list is not empty.
461        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
462
463        verifyRemoveNetworkFromWifiConfigManager(openNetwork);
464        // Ensure that configured network list is empty now.
465        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
466    }
467
468    /**
469     * Verifies the removal of an ephemeral network using
470     * {@link WifiConfigManager#removeNetwork(int)}
471     */
472    @Test
473    public void testRemoveSingleEphemeralNetwork() throws Exception {
474        WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
475        ephemeralNetwork.ephemeral = true;
476
477        verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
478        // Ensure that configured network list is not empty.
479        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
480
481        verifyRemoveEphemeralNetworkFromWifiConfigManager(ephemeralNetwork);
482        // Ensure that configured network list is empty now.
483        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
484    }
485
486    /**
487     * Verifies the removal of a Passpoint network using
488     * {@link WifiConfigManager#removeNetwork(int)}
489     */
490    @Test
491    public void testRemoveSinglePasspointNetwork() throws Exception {
492        WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
493
494        verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
495        // Ensure that configured network list is not empty.
496        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
497
498        verifyRemovePasspointNetworkFromWifiConfigManager(passpointNetwork);
499        // Ensure that configured network list is empty now.
500        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
501    }
502
503    /**
504     * Verifies the addition & update of multiple networks using
505     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and the
506     * removal of networks using
507     * {@link WifiConfigManager#removeNetwork(int)}
508     */
509    @Test
510    public void testAddUpdateRemoveMultipleNetworks() {
511        List<WifiConfiguration> networks = new ArrayList<>();
512        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
513        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
514        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
515        networks.add(openNetwork);
516        networks.add(pskNetwork);
517        networks.add(wepNetwork);
518
519        verifyAddNetworkToWifiConfigManager(openNetwork);
520        verifyAddNetworkToWifiConfigManager(pskNetwork);
521        verifyAddNetworkToWifiConfigManager(wepNetwork);
522
523        // Now verify that all the additions has been effective.
524        List<WifiConfiguration> retrievedNetworks =
525                mWifiConfigManager.getConfiguredNetworksWithPasswords();
526        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
527                networks, retrievedNetworks);
528
529        // Modify all the 3 configurations and update it to WifiConfigManager.
530        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
531        assertAndSetNetworkBSSID(pskNetwork, TEST_BSSID);
532        assertAndSetNetworkIpConfiguration(
533                wepNetwork,
534                WifiConfigurationTestUtil.createStaticIpConfigurationWithPacProxy());
535
536        // Configure mock DevicePolicyManager to give Profile Owner permission so that we can modify
537        // proxy settings on a configuration
538        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(),
539                eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))).thenReturn(true);
540
541        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
542        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork);
543        verifyUpdateNetworkToWifiConfigManagerWithIpChange(wepNetwork);
544        // Now verify that all the modifications has been effective.
545        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
546        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
547                networks, retrievedNetworks);
548
549        // Now remove all 3 networks.
550        verifyRemoveNetworkFromWifiConfigManager(openNetwork);
551        verifyRemoveNetworkFromWifiConfigManager(pskNetwork);
552        verifyRemoveNetworkFromWifiConfigManager(wepNetwork);
553
554        // Ensure that configured network list is empty now.
555        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
556    }
557
558    /**
559     * Verifies the update of network status using
560     * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)}.
561     */
562    @Test
563    public void testNetworkSelectionStatus() {
564        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
565
566        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
567
568        // First set it to enabled.
569        verifyUpdateNetworkSelectionStatus(
570                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
571
572        // Now set it to temporarily disabled. The threshold for association rejection is 5, so
573        // disable it 5 times to actually mark it temporarily disabled.
574        int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
575        int assocRejectThreshold =
576                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason];
577        for (int i = 1; i <= assocRejectThreshold; i++) {
578            verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i);
579        }
580
581        // Now set it to permanently disabled.
582        verifyUpdateNetworkSelectionStatus(
583                result.getNetworkId(), NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER, 0);
584
585        // Now set it back to enabled.
586        verifyUpdateNetworkSelectionStatus(
587                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
588    }
589
590    /**
591     * Verifies the update of network status using
592     * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and ensures that
593     * enabling a network clears out all the temporary disable counters.
594     */
595    @Test
596    public void testNetworkSelectionStatusEnableClearsDisableCounters() {
597        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
598
599        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
600
601        // First set it to enabled.
602        verifyUpdateNetworkSelectionStatus(
603                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
604
605        // Now set it to temporarily disabled 2 times for 2 different reasons.
606        verifyUpdateNetworkSelectionStatus(
607                result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1);
608        verifyUpdateNetworkSelectionStatus(
609                result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 2);
610        verifyUpdateNetworkSelectionStatus(
611                result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1);
612        verifyUpdateNetworkSelectionStatus(
613                result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 2);
614
615        // Now set it back to enabled.
616        verifyUpdateNetworkSelectionStatus(
617                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
618
619        // Ensure that the counters have all been reset now.
620        verifyUpdateNetworkSelectionStatus(
621                result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1);
622        verifyUpdateNetworkSelectionStatus(
623                result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1);
624    }
625
626    /**
627     * Verifies that {@link WifiConfigManager#updateNetworkNotRecommended(int, boolean)} correctly
628     * updates the {@link NetworkSelectionStatus#mNotRecommended} bit.
629     */
630    @Test
631    public void testUpdateNetworkNotRecommended() {
632        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
633
634        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
635
636        // First retrieve the configuration and check this it does not have this bit set
637        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.netId);
638
639        assertFalse(retrievedNetwork.getNetworkSelectionStatus().isNotRecommended());
640
641        // Update the network to be not recommended;
642        assertTrue(mWifiConfigManager.updateNetworkNotRecommended(
643                result.netId, true /* notRecommended*/));
644
645        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.netId);
646
647        assertTrue(retrievedNetwork.getNetworkSelectionStatus().isNotRecommended());
648
649        // Update the network to no longer be not recommended
650        assertTrue(mWifiConfigManager.updateNetworkNotRecommended(
651                result.netId, false/* notRecommended*/));
652
653        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.netId);
654
655        assertFalse(retrievedNetwork.getNetworkSelectionStatus().isNotRecommended());
656    }
657
658    /**
659     * Verifies the enabling of temporarily disabled network using
660     * {@link WifiConfigManager#tryEnableNetwork(int)}.
661     */
662    @Test
663    public void testTryEnableNetwork() {
664        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
665
666        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
667
668        // First set it to enabled.
669        verifyUpdateNetworkSelectionStatus(
670                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
671
672        // Now set it to temporarily disabled. The threshold for association rejection is 5, so
673        // disable it 5 times to actually mark it temporarily disabled.
674        int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
675        int assocRejectThreshold =
676                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason];
677        for (int i = 1; i <= assocRejectThreshold; i++) {
678            verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i);
679        }
680
681        // Now let's try enabling this network without changing the time, this should fail and the
682        // status remains temporarily disabled.
683        assertFalse(mWifiConfigManager.tryEnableNetwork(result.getNetworkId()));
684        NetworkSelectionStatus retrievedStatus =
685                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
686                        .getNetworkSelectionStatus();
687        assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
688
689        // Now advance time by the timeout for association rejection and ensure that the network
690        // is now enabled.
691        int assocRejectTimeout =
692                WifiConfigManager.NETWORK_SELECTION_DISABLE_TIMEOUT_MS[assocRejectReason];
693        when(mClock.getElapsedSinceBootMillis())
694                .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS + assocRejectTimeout);
695
696        assertTrue(mWifiConfigManager.tryEnableNetwork(result.getNetworkId()));
697        retrievedStatus =
698                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
699                        .getNetworkSelectionStatus();
700        assertTrue(retrievedStatus.isNetworkEnabled());
701    }
702
703    /**
704     * Verifies the enabling of network using
705     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} and
706     * {@link WifiConfigManager#disableNetwork(int, int)}.
707     */
708    @Test
709    public void testEnableDisableNetwork() {
710        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
711
712        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
713
714        assertTrue(mWifiConfigManager.enableNetwork(
715                result.getNetworkId(), false, TEST_CREATOR_UID));
716        WifiConfiguration retrievedNetwork =
717                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
718        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
719        assertTrue(retrievedStatus.isNetworkEnabled());
720        verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
721
722        // Now set it disabled.
723        assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID));
724        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
725        retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
726        assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
727        verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
728    }
729
730    /**
731     * Verifies the enabling of network using
732     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with a UID which
733     * has no permission to modify the network fails..
734     */
735    @Test
736    public void testEnableDisableNetworkFailedDueToPermissionDenied() throws Exception {
737        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
738
739        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
740
741        assertTrue(mWifiConfigManager.enableNetwork(
742                result.getNetworkId(), false, TEST_CREATOR_UID));
743        WifiConfiguration retrievedNetwork =
744                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
745        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
746        assertTrue(retrievedStatus.isNetworkEnabled());
747        verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
748
749        // Deny permission for |UPDATE_UID|.
750        doAnswer(new AnswerWithArguments() {
751            public int answer(String permName, int uid) throws Exception {
752                if (uid == TEST_CREATOR_UID) {
753                    return PackageManager.PERMISSION_GRANTED;
754                }
755                return PackageManager.PERMISSION_DENIED;
756            }
757        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
758
759        // Now try to set it disabled with |TEST_UPDATE_UID|, it should fail and the network
760        // should remain enabled.
761        assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_UPDATE_UID));
762        retrievedStatus =
763                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
764                        .getNetworkSelectionStatus();
765        assertTrue(retrievedStatus.isNetworkEnabled());
766        assertEquals(WifiConfiguration.Status.ENABLED, retrievedNetwork.status);
767    }
768
769    /**
770     * Verifies the updation of network's connectUid using
771     * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}.
772     */
773    @Test
774    public void testUpdateLastConnectUid() throws Exception {
775        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
776
777        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
778
779        assertTrue(
780                mWifiConfigManager.checkAndUpdateLastConnectUid(
781                        result.getNetworkId(), TEST_CREATOR_UID));
782        WifiConfiguration retrievedNetwork =
783                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
784        assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid);
785
786        // Deny permission for |UPDATE_UID|.
787        doAnswer(new AnswerWithArguments() {
788            public int answer(String permName, int uid) throws Exception {
789                if (uid == TEST_CREATOR_UID) {
790                    return PackageManager.PERMISSION_GRANTED;
791                }
792                return PackageManager.PERMISSION_DENIED;
793            }
794        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
795
796        // Now try to update the last connect UID with |TEST_UPDATE_UID|, it should fail and
797        // the lastConnectUid should remain the same.
798        assertFalse(
799                mWifiConfigManager.checkAndUpdateLastConnectUid(
800                        result.getNetworkId(), TEST_UPDATE_UID));
801        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
802        assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid);
803    }
804
805    /**
806     * Verifies that any configuration update attempt with an null config is gracefully
807     * handled.
808     * This invokes {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
809     */
810    @Test
811    public void testAddOrUpdateNetworkWithNullConfig() {
812        NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(null, TEST_CREATOR_UID);
813        assertFalse(result.isSuccess());
814    }
815
816    /**
817     * Verifies that attempting to remove a network without any configs stored will return false.
818     * This tests the case where we have not loaded any configs, potentially due to a pending store
819     * read.
820     * This invokes {@link WifiConfigManager#removeNetwork(int)}.
821     */
822    @Test
823    public void testRemoveNetworkWithEmptyConfigStore() {
824        int networkId = new Random().nextInt();
825        assertFalse(mWifiConfigManager.removeNetwork(networkId, TEST_CREATOR_UID));
826    }
827
828    /**
829     * Verifies that any configuration removal attempt with an invalid networkID is gracefully
830     * handled.
831     * This invokes {@link WifiConfigManager#removeNetwork(int)}.
832     */
833    @Test
834    public void testRemoveNetworkWithInvalidNetworkId() {
835        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
836
837        verifyAddNetworkToWifiConfigManager(openNetwork);
838
839        // Change the networkID to an invalid one.
840        openNetwork.networkId++;
841        assertFalse(mWifiConfigManager.removeNetwork(openNetwork.networkId, TEST_CREATOR_UID));
842    }
843
844    /**
845     * Verifies that any configuration update attempt with an invalid networkID is gracefully
846     * handled.
847     * This invokes {@link WifiConfigManager#enableNetwork(int, boolean, int)},
848     * {@link WifiConfigManager#disableNetwork(int, int)},
849     * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and
850     * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}.
851     */
852    @Test
853    public void testChangeConfigurationWithInvalidNetworkId() {
854        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
855
856        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
857
858        assertFalse(mWifiConfigManager.enableNetwork(
859                result.getNetworkId() + 1, false, TEST_CREATOR_UID));
860        assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId() + 1, TEST_CREATOR_UID));
861        assertFalse(mWifiConfigManager.updateNetworkSelectionStatus(
862                result.getNetworkId() + 1, NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER));
863        assertFalse(mWifiConfigManager.checkAndUpdateLastConnectUid(
864                result.getNetworkId() + 1, TEST_CREATOR_UID));
865    }
866
867    /**
868     * Verifies multiple modification of a single network using
869     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
870     * This test is basically checking if the apps can reset some of the fields of the config after
871     * addition. The fields being reset in this test are the |preSharedKey| and |wepKeys|.
872     * 1. Create an open network initially.
873     * 2. Modify the added network config to a WEP network config with all the 4 keys set.
874     * 3. Modify the added network config to a WEP network config with only 1 key set.
875     * 4. Modify the added network config to a PSK network config.
876     */
877    @Test
878    public void testMultipleUpdatesSingleNetwork() {
879        WifiConfiguration network = WifiConfigurationTestUtil.createOpenNetwork();
880        verifyAddNetworkToWifiConfigManager(network);
881
882        // Now add |wepKeys| to the network. We don't need to update the |allowedKeyManagement|
883        // fields for open to WEP conversion.
884        String[] wepKeys =
885                Arrays.copyOf(WifiConfigurationTestUtil.TEST_WEP_KEYS,
886                        WifiConfigurationTestUtil.TEST_WEP_KEYS.length);
887        int wepTxKeyIdx = WifiConfigurationTestUtil.TEST_WEP_TX_KEY_INDEX;
888        assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
889
890        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
891        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
892                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
893
894        // Now empty out 3 of the |wepKeys[]| and ensure that those keys have been reset correctly.
895        for (int i = 1; i < network.wepKeys.length; i++) {
896            wepKeys[i] = "";
897        }
898        wepTxKeyIdx = 0;
899        assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
900
901        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
902        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
903                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
904
905        // Now change the config to a PSK network config by resetting the remaining |wepKey[0]|
906        // field and setting the |preSharedKey| and |allowedKeyManagement| fields.
907        wepKeys[0] = "";
908        wepTxKeyIdx = -1;
909        assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
910        network.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
911        assertAndSetNetworkPreSharedKey(network, WifiConfigurationTestUtil.TEST_PSK);
912
913        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
914        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
915                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
916    }
917
918    /**
919     * Verifies the modification of a WifiEnteriseConfig using
920     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
921     */
922    @Test
923    public void testUpdateWifiEnterpriseConfig() {
924        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
925        verifyAddNetworkToWifiConfigManager(network);
926
927        // Set the |password| field in WifiEnterpriseConfig and modify the config to PEAP/GTC.
928        network.enterpriseConfig =
929                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
930        assertAndSetNetworkEnterprisePassword(network, "test");
931
932        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
933        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
934                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
935
936        // Reset the |password| field in WifiEnterpriseConfig and modify the config to TLS/None.
937        network.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
938        network.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);
939        assertAndSetNetworkEnterprisePassword(network, "");
940
941        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
942        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
943                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
944    }
945
946    /**
947     * Verifies the modification of a single network using
948     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} by passing in nulls
949     * in all the publicly exposed fields.
950     */
951    @Test
952    public void testUpdateSingleNetworkWithNullValues() {
953        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
954        verifyAddNetworkToWifiConfigManager(network);
955
956        // Save a copy of the original network for comparison.
957        WifiConfiguration originalNetwork = new WifiConfiguration(network);
958
959        // Now set all the public fields to null and try updating the network.
960        network.allowedAuthAlgorithms.clear();
961        network.allowedProtocols.clear();
962        network.allowedKeyManagement.clear();
963        network.allowedPairwiseCiphers.clear();
964        network.allowedGroupCiphers.clear();
965        network.setIpConfiguration(null);
966        network.enterpriseConfig = null;
967
968        // Update the network.
969        NetworkUpdateResult result = updateNetworkToWifiConfigManager(network);
970        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
971        assertFalse(result.isNewNetwork());
972
973        // Verify no changes to the original network configuration.
974        verifyNetworkUpdateBroadcast(originalNetwork);
975        verifyNetworkInConfigStoreData(originalNetwork);
976        assertFalse(result.hasIpChanged());
977        assertFalse(result.hasProxyChanged());
978
979        // Copy over the updated debug params to the original network config before comparison.
980        originalNetwork.lastUpdateUid = network.lastUpdateUid;
981        originalNetwork.lastUpdateName = network.lastUpdateName;
982        originalNetwork.updateTime = network.updateTime;
983
984        // Now verify that there was no change to the network configurations.
985        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
986                originalNetwork,
987                mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId));
988    }
989
990    /**
991     * Verifies that the modification of a single network using
992     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} does not modify
993     * existing configuration if there is a failure.
994     */
995    @Test
996    public void testUpdateSingleNetworkFailureDoesNotModifyOriginal() {
997        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
998        network.enterpriseConfig =
999                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
1000        verifyAddNetworkToWifiConfigManager(network);
1001
1002        // Save a copy of the original network for comparison.
1003        WifiConfiguration originalNetwork = new WifiConfiguration(network);
1004
1005        // Now modify the network's EAP method.
1006        network.enterpriseConfig =
1007                WifiConfigurationTestUtil.createTLSWifiEnterpriseConfigWithNonePhase2();
1008
1009        // Fail this update because of cert installation failure.
1010        when(mWifiKeyStore
1011                .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class)))
1012                .thenReturn(false);
1013        NetworkUpdateResult result =
1014                mWifiConfigManager.addOrUpdateNetwork(network, TEST_UPDATE_UID);
1015        assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
1016
1017        // Now verify that there was no change to the network configurations.
1018        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1019                originalNetwork,
1020                mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId));
1021    }
1022
1023    /**
1024     * Verifies the matching of networks with different encryption types with the
1025     * corresponding scan detail using
1026     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)}.
1027     * The test also verifies that the provided scan detail was cached,
1028     */
1029    @Test
1030    public void testMatchScanDetailToNetworksAndCache() {
1031        // Create networks of different types and ensure that they're all matched using
1032        // the corresponding ScanDetail correctly.
1033        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1034                WifiConfigurationTestUtil.createOpenNetwork());
1035        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1036                WifiConfigurationTestUtil.createWepNetwork());
1037        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1038                WifiConfigurationTestUtil.createPskNetwork());
1039        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1040                WifiConfigurationTestUtil.createEapNetwork());
1041    }
1042
1043    /**
1044     * Verifies that scan details with wrong SSID/authentication types are not matched using
1045     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)}
1046     * to the added networks.
1047     */
1048    @Test
1049    public void testNoMatchScanDetailToNetwork() {
1050        // First create networks of different types.
1051        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1052        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1053        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1054        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
1055
1056        // Now add them to WifiConfigManager.
1057        verifyAddNetworkToWifiConfigManager(openNetwork);
1058        verifyAddNetworkToWifiConfigManager(wepNetwork);
1059        verifyAddNetworkToWifiConfigManager(pskNetwork);
1060        verifyAddNetworkToWifiConfigManager(eapNetwork);
1061
1062        // Now create dummy scan detail corresponding to the networks.
1063        ScanDetail openNetworkScanDetail = createScanDetailForNetwork(openNetwork);
1064        ScanDetail wepNetworkScanDetail = createScanDetailForNetwork(wepNetwork);
1065        ScanDetail pskNetworkScanDetail = createScanDetailForNetwork(pskNetwork);
1066        ScanDetail eapNetworkScanDetail = createScanDetailForNetwork(eapNetwork);
1067
1068        // Now mix and match parameters from different scan details.
1069        openNetworkScanDetail.getScanResult().SSID =
1070                wepNetworkScanDetail.getScanResult().SSID;
1071        wepNetworkScanDetail.getScanResult().capabilities =
1072                pskNetworkScanDetail.getScanResult().capabilities;
1073        pskNetworkScanDetail.getScanResult().capabilities =
1074                eapNetworkScanDetail.getScanResult().capabilities;
1075        eapNetworkScanDetail.getScanResult().capabilities =
1076                openNetworkScanDetail.getScanResult().capabilities;
1077
1078        // Try to lookup a saved network using the modified scan details. All of these should fail.
1079        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(openNetworkScanDetail));
1080        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(wepNetworkScanDetail));
1081        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(pskNetworkScanDetail));
1082        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(eapNetworkScanDetail));
1083
1084        // All the cache's should be empty as well.
1085        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId));
1086        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(wepNetwork.networkId));
1087        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(pskNetwork.networkId));
1088        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(eapNetwork.networkId));
1089    }
1090
1091    /**
1092     * Verifies that ScanDetail added for a network is cached correctly.
1093     */
1094    @Test
1095    public void testUpdateScanDetailForNetwork() {
1096        // First add the provided network.
1097        WifiConfiguration testNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1098        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(testNetwork);
1099
1100        // Now create a dummy scan detail corresponding to the network.
1101        ScanDetail scanDetail = createScanDetailForNetwork(testNetwork);
1102        ScanResult scanResult = scanDetail.getScanResult();
1103
1104        mWifiConfigManager.updateScanDetailForNetwork(result.getNetworkId(), scanDetail);
1105
1106        // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
1107        ScanDetailCache retrievedScanDetailCache =
1108                mWifiConfigManager.getScanDetailCacheForNetwork(result.getNetworkId());
1109        assertEquals(1, retrievedScanDetailCache.size());
1110        ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID);
1111
1112        ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
1113    }
1114
1115    /**
1116     * Verifies that scan detail cache is trimmed down when the size of the cache for a network
1117     * exceeds {@link WifiConfigManager#SCAN_CACHE_ENTRIES_MAX_SIZE}.
1118     */
1119    @Test
1120    public void testScanDetailCacheTrimForNetwork() {
1121        // Add a single network.
1122        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1123        verifyAddNetworkToWifiConfigManager(openNetwork);
1124
1125        ScanDetailCache scanDetailCache;
1126        String testBssidPrefix = "00:a5:b8:c9:45:";
1127
1128        // Modify |BSSID| field in the scan result and add copies of scan detail
1129        // |SCAN_CACHE_ENTRIES_MAX_SIZE| times.
1130        int scanDetailNum = 1;
1131        for (; scanDetailNum <= WifiConfigManager.SCAN_CACHE_ENTRIES_MAX_SIZE; scanDetailNum++) {
1132            // Create dummy scan detail caches with different BSSID for the network.
1133            ScanDetail scanDetail =
1134                    createScanDetailForNetwork(
1135                            openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum));
1136            assertNotNull(
1137                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail));
1138
1139            // The size of scan detail cache should keep growing until it hits
1140            // |SCAN_CACHE_ENTRIES_MAX_SIZE|.
1141            scanDetailCache =
1142                    mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId);
1143            assertEquals(scanDetailNum, scanDetailCache.size());
1144        }
1145
1146        // Now add the |SCAN_CACHE_ENTRIES_MAX_SIZE + 1| entry. This should trigger the trim.
1147        ScanDetail scanDetail =
1148                createScanDetailForNetwork(
1149                        openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum));
1150        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail));
1151
1152        // Retrieve the scan detail cache and ensure that the size was trimmed down to
1153        // |SCAN_CACHE_ENTRIES_TRIM_SIZE + 1|. The "+1" is to account for the new entry that
1154        // was added after the trim.
1155        scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId);
1156        assertEquals(WifiConfigManager.SCAN_CACHE_ENTRIES_TRIM_SIZE + 1, scanDetailCache.size());
1157    }
1158
1159    /**
1160     * Verifies that hasEverConnected is false for a newly added network.
1161     */
1162    @Test
1163    public void testAddNetworkHasEverConnectedFalse() {
1164        verifyAddNetworkHasEverConnectedFalse(WifiConfigurationTestUtil.createOpenNetwork());
1165    }
1166
1167    /**
1168     * Verifies that hasEverConnected is false for a newly added network even when new config has
1169     * mistakenly set HasEverConnected to true.
1170     */
1171    @Test
1172    public void testAddNetworkOverridesHasEverConnectedWhenTrueInNewConfig() {
1173        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1174        openNetwork.getNetworkSelectionStatus().setHasEverConnected(true);
1175        verifyAddNetworkHasEverConnectedFalse(openNetwork);
1176    }
1177
1178    /**
1179     * Verify that the |HasEverConnected| is set when
1180     * {@link WifiConfigManager#updateNetworkAfterConnect(int)} is invoked.
1181     */
1182    @Test
1183    public void testUpdateConfigAfterConnectHasEverConnectedTrue() {
1184        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1185        verifyAddNetworkHasEverConnectedFalse(openNetwork);
1186        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(openNetwork.networkId);
1187    }
1188
1189    /**
1190     * Verifies that hasEverConnected is cleared when a network config |preSharedKey| is updated.
1191     */
1192    @Test
1193    public void testUpdatePreSharedKeyClearsHasEverConnected() {
1194        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1195        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1196        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1197
1198        // Now update the same network with a different psk.
1199        assertFalse(pskNetwork.preSharedKey.equals("newpassword"));
1200        pskNetwork.preSharedKey = "newpassword";
1201        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1202    }
1203
1204    /**
1205     * Verifies that hasEverConnected is cleared when a network config |wepKeys| is updated.
1206     */
1207    @Test
1208    public void testUpdateWepKeysClearsHasEverConnected() {
1209        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1210        verifyAddNetworkHasEverConnectedFalse(wepNetwork);
1211        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId);
1212
1213        // Now update the same network with a different wep.
1214        assertFalse(wepNetwork.wepKeys[0].equals("newpassword"));
1215        wepNetwork.wepKeys[0] = "newpassword";
1216        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork);
1217    }
1218
1219    /**
1220     * Verifies that hasEverConnected is cleared when a network config |wepTxKeyIndex| is updated.
1221     */
1222    @Test
1223    public void testUpdateWepTxKeyClearsHasEverConnected() {
1224        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1225        verifyAddNetworkHasEverConnectedFalse(wepNetwork);
1226        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId);
1227
1228        // Now update the same network with a different wep.
1229        assertFalse(wepNetwork.wepTxKeyIndex == 3);
1230        wepNetwork.wepTxKeyIndex = 3;
1231        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork);
1232    }
1233
1234    /**
1235     * Verifies that hasEverConnected is cleared when a network config |allowedKeyManagement| is
1236     * updated.
1237     */
1238    @Test
1239    public void testUpdateAllowedKeyManagementClearsHasEverConnected() {
1240        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1241        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1242        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1243
1244        assertFalse(pskNetwork.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X));
1245        pskNetwork.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
1246        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1247    }
1248
1249    /**
1250     * Verifies that hasEverConnected is cleared when a network config |allowedProtocol| is
1251     * updated.
1252     */
1253    @Test
1254    public void testUpdateProtocolsClearsHasEverConnected() {
1255        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1256        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1257        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1258
1259        assertFalse(pskNetwork.allowedProtocols.get(WifiConfiguration.Protocol.OSEN));
1260        pskNetwork.allowedProtocols.set(WifiConfiguration.Protocol.OSEN);
1261        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1262    }
1263
1264    /**
1265     * Verifies that hasEverConnected is cleared when a network config |allowedAuthAlgorithms| is
1266     * updated.
1267     */
1268    @Test
1269    public void testUpdateAllowedAuthAlgorithmsClearsHasEverConnected() {
1270        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1271        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1272        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1273
1274        assertFalse(pskNetwork.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.LEAP));
1275        pskNetwork.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP);
1276        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1277    }
1278
1279    /**
1280     * Verifies that hasEverConnected is cleared when a network config |allowedPairwiseCiphers| is
1281     * updated.
1282     */
1283    @Test
1284    public void testUpdateAllowedPairwiseCiphersClearsHasEverConnected() {
1285        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1286        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1287        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1288
1289        assertFalse(pskNetwork.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.NONE));
1290        pskNetwork.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
1291        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1292    }
1293
1294    /**
1295     * Verifies that hasEverConnected is cleared when a network config |allowedGroup| is
1296     * updated.
1297     */
1298    @Test
1299    public void testUpdateAllowedGroupCiphersClearsHasEverConnected() {
1300        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1301        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1302        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1303
1304        assertTrue(pskNetwork.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP104));
1305        pskNetwork.allowedGroupCiphers.clear(WifiConfiguration.GroupCipher.WEP104);
1306        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1307    }
1308
1309    /**
1310     * Verifies that hasEverConnected is cleared when a network config |hiddenSSID| is
1311     * updated.
1312     */
1313    @Test
1314    public void testUpdateHiddenSSIDClearsHasEverConnected() {
1315        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1316        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1317        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1318
1319        assertFalse(pskNetwork.hiddenSSID);
1320        pskNetwork.hiddenSSID = true;
1321        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1322    }
1323
1324    /**
1325     * Verifies that hasEverConnected is not cleared when a network config |requirePMF| is
1326     * updated.
1327     */
1328    @Test
1329    public void testUpdateRequirePMFDoesNotClearHasEverConnected() {
1330        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1331        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1332        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1333
1334        assertFalse(pskNetwork.requirePMF);
1335        pskNetwork.requirePMF = true;
1336
1337        NetworkUpdateResult result =
1338                verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork);
1339        WifiConfiguration retrievedNetwork =
1340                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1341        assertTrue("Updating network non-credentials config should not clear hasEverConnected.",
1342                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
1343    }
1344
1345    /**
1346     * Verifies that hasEverConnected is cleared when a network config |enterpriseConfig| is
1347     * updated.
1348     */
1349    @Test
1350    public void testUpdateEnterpriseConfigClearsHasEverConnected() {
1351        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
1352        eapNetwork.enterpriseConfig =
1353                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
1354        verifyAddNetworkHasEverConnectedFalse(eapNetwork);
1355        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(eapNetwork.networkId);
1356
1357        assertFalse(eapNetwork.enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS);
1358        eapNetwork.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
1359        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(eapNetwork);
1360    }
1361
1362    /**
1363     * Verifies the ordering of network list generated using
1364     * {@link WifiConfigManager#retrievePnoNetworkList()}.
1365     */
1366    @Test
1367    public void testRetrievePnoList() {
1368        // Create and add 3 networks.
1369        WifiConfiguration network1 = WifiConfigurationTestUtil.createEapNetwork();
1370        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1371        WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork();
1372        verifyAddNetworkToWifiConfigManager(network1);
1373        verifyAddNetworkToWifiConfigManager(network2);
1374        verifyAddNetworkToWifiConfigManager(network3);
1375
1376        // Enable all of them.
1377        assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID));
1378        assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID));
1379        assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID));
1380
1381        // Now set scan results in 2 of them to set the corresponding
1382        // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field.
1383        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
1384                network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54));
1385        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
1386                network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54));
1387
1388        // Now increment |network3|'s association count. This should ensure that this network
1389        // is preferred over |network1|.
1390        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId));
1391
1392        // Retrieve the Pno network list & verify the order of the networks returned.
1393        List<WifiScanner.PnoSettings.PnoNetwork> pnoNetworks =
1394                mWifiConfigManager.retrievePnoNetworkList();
1395        assertEquals(3, pnoNetworks.size());
1396        assertEquals(network3.SSID, pnoNetworks.get(0).ssid);
1397        assertEquals(network1.SSID, pnoNetworks.get(1).ssid);
1398        assertEquals(network2.SSID, pnoNetworks.get(2).ssid);
1399
1400        // Now permanently disable |network3|. This should remove network 3 from the list.
1401        assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID));
1402
1403        // Retrieve the Pno network list again & verify the order of the networks returned.
1404        pnoNetworks = mWifiConfigManager.retrievePnoNetworkList();
1405        assertEquals(2, pnoNetworks.size());
1406        assertEquals(network1.SSID, pnoNetworks.get(0).ssid);
1407        assertEquals(network2.SSID, pnoNetworks.get(1).ssid);
1408    }
1409
1410    /**
1411     * Verifies the linking of networks when they have the same default GW Mac address in
1412     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1413     */
1414    @Test
1415    public void testNetworkLinkUsingGwMacAddress() {
1416        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1417        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1418        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
1419        verifyAddNetworkToWifiConfigManager(network1);
1420        verifyAddNetworkToWifiConfigManager(network2);
1421        verifyAddNetworkToWifiConfigManager(network3);
1422
1423        // Set the same default GW mac address for all of the networks.
1424        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1425                network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1426        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1427                network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1428        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1429                network3.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1430
1431        // Now create dummy scan detail corresponding to the networks.
1432        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1);
1433        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2);
1434        ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3);
1435
1436        // Now save all these scan details corresponding to each of this network and expect
1437        // all of these networks to be linked with each other.
1438        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1439        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1440        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3));
1441
1442        List<WifiConfiguration> retrievedNetworks =
1443                mWifiConfigManager.getConfiguredNetworks();
1444        for (WifiConfiguration network : retrievedNetworks) {
1445            assertEquals(2, network.linkedConfigurations.size());
1446            for (WifiConfiguration otherNetwork : retrievedNetworks) {
1447                if (otherNetwork == network) {
1448                    continue;
1449                }
1450                assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey()));
1451            }
1452        }
1453    }
1454
1455    /**
1456     * Verifies the linking of networks when they have scan results with same first 16 ASCII of
1457     * bssid in
1458     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1459     */
1460    @Test
1461    public void testNetworkLinkUsingBSSIDMatch() {
1462        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1463        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1464        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
1465        verifyAddNetworkToWifiConfigManager(network1);
1466        verifyAddNetworkToWifiConfigManager(network2);
1467        verifyAddNetworkToWifiConfigManager(network3);
1468
1469        // Create scan results with bssid which is different in only the last char.
1470        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
1471        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
1472        ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3, "af:89:56:34:56:69");
1473
1474        // Now save all these scan details corresponding to each of this network and expect
1475        // all of these networks to be linked with each other.
1476        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1477        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1478        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3));
1479
1480        List<WifiConfiguration> retrievedNetworks =
1481                mWifiConfigManager.getConfiguredNetworks();
1482        for (WifiConfiguration network : retrievedNetworks) {
1483            assertEquals(2, network.linkedConfigurations.size());
1484            for (WifiConfiguration otherNetwork : retrievedNetworks) {
1485                if (otherNetwork == network) {
1486                    continue;
1487                }
1488                assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey()));
1489            }
1490        }
1491    }
1492
1493    /**
1494     * Verifies the linking of networks does not happen for non WPA networks when they have scan
1495     * results with same first 16 ASCII of bssid in
1496     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1497     */
1498    @Test
1499    public void testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks() {
1500        WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
1501        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1502        verifyAddNetworkToWifiConfigManager(network1);
1503        verifyAddNetworkToWifiConfigManager(network2);
1504
1505        // Create scan results with bssid which is different in only the last char.
1506        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
1507        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
1508
1509        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1510        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1511
1512        List<WifiConfiguration> retrievedNetworks =
1513                mWifiConfigManager.getConfiguredNetworks();
1514        for (WifiConfiguration network : retrievedNetworks) {
1515            assertNull(network.linkedConfigurations);
1516        }
1517    }
1518
1519    /**
1520     * Verifies the linking of networks does not happen for networks with more than
1521     * {@link WifiConfigManager#LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES} scan
1522     * results with same first 16 ASCII of bssid in
1523     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1524     */
1525    @Test
1526    public void testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize() {
1527        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1528        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1529        verifyAddNetworkToWifiConfigManager(network1);
1530        verifyAddNetworkToWifiConfigManager(network2);
1531
1532        // Create 7 scan results with bssid which is different in only the last char.
1533        String test_bssid_base = "af:89:56:34:56:6";
1534        int scan_result_num = 0;
1535        for (; scan_result_num < WifiConfigManager.LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES + 1;
1536             scan_result_num++) {
1537            ScanDetail networkScanDetail =
1538                    createScanDetailForNetwork(
1539                            network1, test_bssid_base + Integer.toString(scan_result_num));
1540            assertNotNull(
1541                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1542        }
1543
1544        // Now add 1 scan result to the other network with bssid which is different in only the
1545        // last char.
1546        ScanDetail networkScanDetail2 =
1547                createScanDetailForNetwork(
1548                        network2, test_bssid_base + Integer.toString(scan_result_num++));
1549        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1550
1551        List<WifiConfiguration> retrievedNetworks =
1552                mWifiConfigManager.getConfiguredNetworks();
1553        for (WifiConfiguration network : retrievedNetworks) {
1554            assertNull(network.linkedConfigurations);
1555        }
1556    }
1557
1558    /**
1559     * Verifies the linking of networks when they have scan results with same first 16 ASCII of
1560     * bssid in {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}
1561     * and then subsequently delinked when the networks have default gateway set which do not match.
1562     */
1563    @Test
1564    public void testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress() {
1565        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1566        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1567        verifyAddNetworkToWifiConfigManager(network1);
1568        verifyAddNetworkToWifiConfigManager(network2);
1569
1570        // Create scan results with bssid which is different in only the last char.
1571        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
1572        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
1573
1574        // Now save all these scan details corresponding to each of this network and expect
1575        // all of these networks to be linked with each other.
1576        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1577        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1578
1579        List<WifiConfiguration> retrievedNetworks =
1580                mWifiConfigManager.getConfiguredNetworks();
1581        for (WifiConfiguration network : retrievedNetworks) {
1582            assertEquals(1, network.linkedConfigurations.size());
1583            for (WifiConfiguration otherNetwork : retrievedNetworks) {
1584                if (otherNetwork == network) {
1585                    continue;
1586                }
1587                assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey()));
1588            }
1589        }
1590
1591        // Now Set different GW mac address for both the networks and ensure they're unlinked.
1592        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1593                network1.networkId, "de:ad:fe:45:23:34"));
1594        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1595                network2.networkId, "ad:de:fe:45:23:34"));
1596
1597        // Add some dummy scan results again to re-evaluate the linking of networks.
1598        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(
1599                createScanDetailForNetwork(network1, "af:89:56:34:45:67")));
1600        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(
1601                createScanDetailForNetwork(network1, "af:89:56:34:45:68")));
1602
1603        retrievedNetworks = mWifiConfigManager.getConfiguredNetworks();
1604        for (WifiConfiguration network : retrievedNetworks) {
1605            assertNull(network.linkedConfigurations);
1606        }
1607    }
1608
1609    /**
1610     * Verifies the creation of channel list using
1611     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)}.
1612     */
1613    @Test
1614    public void testFetchChannelSetForNetwork() {
1615        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1616        verifyAddNetworkToWifiConfigManager(network);
1617
1618        // Create 5 scan results with different bssid's & frequencies.
1619        String test_bssid_base = "af:89:56:34:56:6";
1620        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1621            ScanDetail networkScanDetail =
1622                    createScanDetailForNetwork(
1623                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1624            assertNotNull(
1625                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1626
1627        }
1628        assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)),
1629                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network.networkId, 1,
1630                        TEST_FREQ_LIST[4]));
1631    }
1632
1633    /**
1634     * Verifies the creation of channel list using
1635     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and
1636     * ensures that the frequenecy of the currently connected network is in the returned
1637     * channel set.
1638     */
1639    @Test
1640    public void testFetchChannelSetForNetworkIncludeCurrentNetwork() {
1641        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1642        verifyAddNetworkToWifiConfigManager(network);
1643
1644        // Create 5 scan results with different bssid's & frequencies.
1645        String test_bssid_base = "af:89:56:34:56:6";
1646        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1647            ScanDetail networkScanDetail =
1648                    createScanDetailForNetwork(
1649                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1650            assertNotNull(
1651                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1652
1653        }
1654
1655        // Currently connected network frequency 2427 is not in the TEST_FREQ_LIST
1656        Set<Integer> freqs = mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1657                network.networkId, 1, 2427);
1658
1659        assertEquals(true, freqs.contains(2427));
1660    }
1661
1662    /**
1663     * Verifies the creation of channel list using
1664     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and
1665     * ensures that scan results which have a timestamp  beyond the provided age are not used
1666     * in the channel list.
1667     */
1668    @Test
1669    public void testFetchChannelSetForNetworkIgnoresStaleScanResults() {
1670        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1671        verifyAddNetworkToWifiConfigManager(network);
1672
1673        long wallClockBase = 0;
1674        // Create 5 scan results with different bssid's & frequencies.
1675        String test_bssid_base = "af:89:56:34:56:6";
1676        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1677            // Increment the seen value in the scan results for each of them.
1678            when(mClock.getWallClockMillis()).thenReturn(wallClockBase + i);
1679            ScanDetail networkScanDetail =
1680                    createScanDetailForNetwork(
1681                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1682            assertNotNull(
1683                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1684
1685        }
1686        int ageInMillis = 4;
1687        // Now fetch only scan results which are 4 millis stale. This should ignore the first
1688        // scan result.
1689        assertEquals(
1690                new HashSet<>(Arrays.asList(
1691                        Arrays.copyOfRange(
1692                                TEST_FREQ_LIST,
1693                                TEST_FREQ_LIST.length - ageInMillis, TEST_FREQ_LIST.length))),
1694                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1695                        network.networkId, ageInMillis, TEST_FREQ_LIST[4]));
1696    }
1697
1698    /**
1699     * Verifies the creation of channel list using
1700     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and
1701     * ensures that the list size does not exceed the max configured for the device.
1702     */
1703    @Test
1704    public void testFetchChannelSetForNetworkIsLimitedToConfiguredSize() {
1705        // Need to recreate the WifiConfigManager instance for this test to modify the config
1706        // value which is read only in the constructor.
1707        int maxListSize = 3;
1708        mResources.setInteger(
1709                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
1710                maxListSize);
1711        createWifiConfigManager();
1712
1713        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1714        verifyAddNetworkToWifiConfigManager(network);
1715
1716        // Create 5 scan results with different bssid's & frequencies.
1717        String test_bssid_base = "af:89:56:34:56:6";
1718        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1719            ScanDetail networkScanDetail =
1720                    createScanDetailForNetwork(
1721                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1722            assertNotNull(
1723                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1724
1725        }
1726        // Ensure that the fetched list size is limited.
1727        assertEquals(maxListSize,
1728                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1729                        network.networkId, 1, TEST_FREQ_LIST[4]).size());
1730    }
1731
1732    /**
1733     * Verifies the creation of channel list using
1734     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and
1735     * ensures that scan results from linked networks are used in the channel list.
1736     */
1737    @Test
1738    public void testFetchChannelSetForNetworkIncludesLinkedNetworks() {
1739        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1740        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1741        verifyAddNetworkToWifiConfigManager(network1);
1742        verifyAddNetworkToWifiConfigManager(network2);
1743
1744        String test_bssid_base = "af:89:56:34:56:6";
1745        int TEST_FREQ_LISTIdx = 0;
1746        // Create 3 scan results with different bssid's & frequencies for network 1.
1747        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) {
1748            ScanDetail networkScanDetail =
1749                    createScanDetailForNetwork(
1750                            network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1751                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1752            assertNotNull(
1753                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1754
1755        }
1756        // Create 3 scan results with different bssid's & frequencies for network 2.
1757        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) {
1758            ScanDetail networkScanDetail =
1759                    createScanDetailForNetwork(
1760                            network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1761                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1762            assertNotNull(
1763                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1764        }
1765
1766        // Link the 2 configurations together using the GwMacAddress.
1767        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1768                network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1769        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1770                network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1771
1772        // The channel list fetched should include scan results from both the linked networks.
1773        assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)),
1774                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network1.networkId, 1,
1775                        TEST_FREQ_LIST[0]));
1776        assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)),
1777                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network2.networkId, 1,
1778                        TEST_FREQ_LIST[0]));
1779    }
1780
1781    /**
1782     * Verifies the creation of channel list using
1783     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and
1784     * ensures that scan results from linked networks are used in the channel list and that the
1785     * list size does not exceed the max configured for the device.
1786     */
1787    @Test
1788    public void testFetchChannelSetForNetworkIncludesLinkedNetworksIsLimitedToConfiguredSize() {
1789        // Need to recreate the WifiConfigManager instance for this test to modify the config
1790        // value which is read only in the constructor.
1791        int maxListSize = 3;
1792        mResources.setInteger(
1793                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
1794                maxListSize);
1795
1796        createWifiConfigManager();
1797        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1798        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1799        verifyAddNetworkToWifiConfigManager(network1);
1800        verifyAddNetworkToWifiConfigManager(network2);
1801
1802        String test_bssid_base = "af:89:56:34:56:6";
1803        int TEST_FREQ_LISTIdx = 0;
1804        // Create 3 scan results with different bssid's & frequencies for network 1.
1805        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) {
1806            ScanDetail networkScanDetail =
1807                    createScanDetailForNetwork(
1808                            network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1809                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1810            assertNotNull(
1811                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1812
1813        }
1814        // Create 3 scan results with different bssid's & frequencies for network 2.
1815        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) {
1816            ScanDetail networkScanDetail =
1817                    createScanDetailForNetwork(
1818                            network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1819                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1820            assertNotNull(
1821                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1822        }
1823
1824        // Link the 2 configurations together using the GwMacAddress.
1825        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1826                network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1827        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1828                network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1829
1830        // Ensure that the fetched list size is limited.
1831        assertEquals(maxListSize,
1832                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1833                        network1.networkId, 1, TEST_FREQ_LIST[0]).size());
1834        assertEquals(maxListSize,
1835                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1836                        network2.networkId, 1, TEST_FREQ_LIST[0]).size());
1837    }
1838
1839    /**
1840     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
1841     * and ensures that any shared private networks networkId is not changed.
1842     * Test scenario:
1843     * 1. Load the shared networks from shared store and user 1 store.
1844     * 2. Switch to user 2 and ensure that the shared network's Id is not changed.
1845     */
1846    @Test
1847    public void testHandleUserSwitchDoesNotChangeSharedNetworksId() throws Exception {
1848        int user1 = TEST_DEFAULT_USER;
1849        int user2 = TEST_DEFAULT_USER + 1;
1850        setupUserProfiles(user2);
1851
1852        int appId = 674;
1853
1854        // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
1855        final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
1856        user1Network.shared = false;
1857        user1Network.creatorUid = UserHandle.getUid(user1, appId);
1858        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
1859        user2Network.shared = false;
1860        user2Network.creatorUid = UserHandle.getUid(user2, appId);
1861        final WifiConfiguration sharedNetwork1 = WifiConfigurationTestUtil.createPskNetwork();
1862        final WifiConfiguration sharedNetwork2 = WifiConfigurationTestUtil.createPskNetwork();
1863
1864        // Set up the store data that is loaded initially.
1865        List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
1866            {
1867                add(sharedNetwork1);
1868                add(sharedNetwork2);
1869            }
1870        };
1871        List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() {
1872            {
1873                add(user1Network);
1874            }
1875        };
1876        setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>());
1877        assertTrue(mWifiConfigManager.loadFromStore());
1878        verify(mWifiConfigStore).read();
1879
1880        // Fetch the network ID's assigned to the shared networks initially.
1881        int sharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID;
1882        int sharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID;
1883        List<WifiConfiguration> retrievedNetworks =
1884                mWifiConfigManager.getConfiguredNetworksWithPasswords();
1885        for (WifiConfiguration network : retrievedNetworks) {
1886            if (network.configKey().equals(sharedNetwork1.configKey())) {
1887                sharedNetwork1Id = network.networkId;
1888            } else if (network.configKey().equals(sharedNetwork2.configKey())) {
1889                sharedNetwork2Id = network.networkId;
1890            }
1891        }
1892        assertTrue(sharedNetwork1Id != WifiConfiguration.INVALID_NETWORK_ID);
1893        assertTrue(sharedNetwork2Id != WifiConfiguration.INVALID_NETWORK_ID);
1894
1895        // Set up the user 2 store data that is loaded at user switch.
1896        List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() {
1897            {
1898                add(user2Network);
1899            }
1900        };
1901        setupStoreDataForUserRead(user2Networks, new HashSet<String>());
1902        // Now switch the user to user 2 and ensure that shared network's IDs have not changed.
1903        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
1904        mWifiConfigManager.handleUserSwitch(user2);
1905        verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
1906
1907        // Again fetch the network ID's assigned to the shared networks and ensure they have not
1908        // changed.
1909        int updatedSharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID;
1910        int updatedSharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID;
1911        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
1912        for (WifiConfiguration network : retrievedNetworks) {
1913            if (network.configKey().equals(sharedNetwork1.configKey())) {
1914                updatedSharedNetwork1Id = network.networkId;
1915            } else if (network.configKey().equals(sharedNetwork2.configKey())) {
1916                updatedSharedNetwork2Id = network.networkId;
1917            }
1918        }
1919        assertEquals(sharedNetwork1Id, updatedSharedNetwork1Id);
1920        assertEquals(sharedNetwork2Id, updatedSharedNetwork2Id);
1921    }
1922
1923    /**
1924     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
1925     * and ensures that any old user private networks are not visible anymore.
1926     * Test scenario:
1927     * 1. Load the shared networks from shared store and user 1 store.
1928     * 2. Switch to user 2 and ensure that the user 1's private network has been removed.
1929     */
1930    @Test
1931    public void testHandleUserSwitchRemovesOldUserPrivateNetworks() throws Exception {
1932        int user1 = TEST_DEFAULT_USER;
1933        int user2 = TEST_DEFAULT_USER + 1;
1934        setupUserProfiles(user2);
1935
1936        int appId = 674;
1937
1938        // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
1939        final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
1940        user1Network.shared = false;
1941        user1Network.creatorUid = UserHandle.getUid(user1, appId);
1942        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
1943        user2Network.shared = false;
1944        user2Network.creatorUid = UserHandle.getUid(user2, appId);
1945        final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
1946
1947        // Set up the store data that is loaded initially.
1948        List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
1949            {
1950                add(sharedNetwork);
1951            }
1952        };
1953        List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() {
1954            {
1955                add(user1Network);
1956            }
1957        };
1958        setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>());
1959        assertTrue(mWifiConfigManager.loadFromStore());
1960        verify(mWifiConfigStore).read();
1961
1962        // Fetch the network ID assigned to the user 1 network initially.
1963        int user1NetworkId = WifiConfiguration.INVALID_NETWORK_ID;
1964        List<WifiConfiguration> retrievedNetworks =
1965                mWifiConfigManager.getConfiguredNetworksWithPasswords();
1966        for (WifiConfiguration network : retrievedNetworks) {
1967            if (network.configKey().equals(user1Network.configKey())) {
1968                user1NetworkId = network.networkId;
1969            }
1970        }
1971
1972        // Set up the user 2 store data that is loaded at user switch.
1973        List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() {
1974            {
1975                add(user2Network);
1976            }
1977        };
1978        setupStoreDataForUserRead(user2Networks, new HashSet<String>());
1979        // Now switch the user to user 2 and ensure that user 1's private network has been removed.
1980        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
1981        Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2);
1982        verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
1983        assertTrue((removedNetworks.size() == 1) && (removedNetworks.contains(user1NetworkId)));
1984
1985        // Set the expected networks to be |sharedNetwork| and |user2Network|.
1986        List<WifiConfiguration> expectedNetworks = new ArrayList<WifiConfiguration>() {
1987            {
1988                add(sharedNetwork);
1989                add(user2Network);
1990            }
1991        };
1992        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1993                expectedNetworks, mWifiConfigManager.getConfiguredNetworksWithPasswords());
1994
1995        // Send another user switch  indication with the same user 2. This should be ignored and
1996        // hence should not remove any new networks.
1997        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
1998        removedNetworks = mWifiConfigManager.handleUserSwitch(user2);
1999        assertTrue(removedNetworks.isEmpty());
2000    }
2001
2002    /**
2003     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2004     * and ensures that user switch from a user with no private networks is handled.
2005     * Test scenario:
2006     * 1. Load the shared networks from shared store and emptu user 1 store.
2007     * 2. Switch to user 2 and ensure that no private networks were removed.
2008     */
2009    @Test
2010    public void testHandleUserSwitchWithNoOldUserPrivateNetworks() throws Exception {
2011        int user1 = TEST_DEFAULT_USER;
2012        int user2 = TEST_DEFAULT_USER + 1;
2013        setupUserProfiles(user2);
2014
2015        int appId = 674;
2016
2017        // Create 2 networks. 1 for user2 and 1 shared.
2018        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2019        user2Network.shared = false;
2020        user2Network.creatorUid = UserHandle.getUid(user2, appId);
2021        final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
2022
2023        // Set up the store data that is loaded initially.
2024        List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
2025            {
2026                add(sharedNetwork);
2027            }
2028        };
2029        setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(),
2030                new HashSet<String>());
2031        assertTrue(mWifiConfigManager.loadFromStore());
2032        verify(mWifiConfigStore).read();
2033
2034        // Set up the user 2 store data that is loaded at user switch.
2035        List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() {
2036            {
2037                add(user2Network);
2038            }
2039        };
2040        setupStoreDataForUserRead(user2Networks, new HashSet<String>());
2041        // Now switch the user to user 2 and ensure that no private network has been removed.
2042        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2043        Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2);
2044        verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2045        assertTrue(removedNetworks.isEmpty());
2046    }
2047
2048    /**
2049     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2050     * and ensures that any non current user private networks are moved to shared store file.
2051     * This test simulates the following test case:
2052     * 1. Loads the shared networks from shared store at bootup.
2053     * 2. Load the private networks from user store on user 1 unlock.
2054     * 3. Switch to user 2 and ensure that the user 2's private network has been moved to user 2's
2055     * private store file.
2056     */
2057    @Test
2058    public void testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore() throws Exception {
2059        int user1 = TEST_DEFAULT_USER;
2060        int user2 = TEST_DEFAULT_USER + 1;
2061        setupUserProfiles(user2);
2062
2063        int appId = 674;
2064
2065        // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
2066        final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
2067        user1Network.shared = false;
2068        user1Network.creatorUid = UserHandle.getUid(user1, appId);
2069        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2070        user2Network.shared = false;
2071        user2Network.creatorUid = UserHandle.getUid(user2, appId);
2072        final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
2073
2074        // Set up the shared store data that is loaded at bootup. User 2's private network
2075        // is still in shared store because they have not yet logged-in after upgrade.
2076        List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
2077            {
2078                add(sharedNetwork);
2079                add(user2Network);
2080            }
2081        };
2082        setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(),
2083                new HashSet<String>());
2084        assertTrue(mWifiConfigManager.loadFromStore());
2085        verify(mWifiConfigStore).read();
2086
2087        // Set up the user store data that is loaded at user unlock.
2088        List<WifiConfiguration> userNetworks = new ArrayList<WifiConfiguration>() {
2089            {
2090                add(user1Network);
2091            }
2092        };
2093        setupStoreDataForUserRead(userNetworks, new HashSet<String>());
2094        mWifiConfigManager.handleUserUnlock(user1);
2095        verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2096        // Capture the written data for the user 1 and ensure that it corresponds to what was
2097        // setup.
2098        Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList =
2099                captureWriteNetworksListStoreData();
2100        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2101                sharedNetworks, writtenNetworkList.first);
2102        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2103                userNetworks, writtenNetworkList.second);
2104
2105        // Now switch the user to user2 and ensure that user 2's private network has been moved to
2106        // the user store.
2107        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2108        mWifiConfigManager.handleUserSwitch(user2);
2109        // Set the expected network list before comparing. user1Network should be in shared data.
2110        // Note: In the real world, user1Network will no longer be visible now because it should
2111        // already be in user1's private store file. But, we're purposefully exposing it
2112        // via |loadStoreData| to test if other user's private networks are pushed to shared store.
2113        List<WifiConfiguration> expectedSharedNetworks = new ArrayList<WifiConfiguration>() {
2114            {
2115                add(sharedNetwork);
2116                add(user1Network);
2117            }
2118        };
2119        List<WifiConfiguration> expectedUserNetworks = new ArrayList<WifiConfiguration>() {
2120            {
2121                add(user2Network);
2122            }
2123        };
2124        // Capture the first written data triggered for saving the old user's network
2125        // configurations.
2126        writtenNetworkList = captureWriteNetworksListStoreData();
2127        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2128                sharedNetworks, writtenNetworkList.first);
2129        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2130                userNetworks, writtenNetworkList.second);
2131
2132        // Now capture the next written data triggered after the switch and ensure that user 2's
2133        // network is now in user store data.
2134        writtenNetworkList = captureWriteNetworksListStoreData();
2135        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2136                expectedSharedNetworks, writtenNetworkList.first);
2137        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2138                expectedUserNetworks, writtenNetworkList.second);
2139    }
2140
2141    /**
2142     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2143     * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is
2144     * read immediately if the user is unlocked during the switch.
2145     */
2146    @Test
2147    public void testHandleUserSwitchWhenUnlocked() throws Exception {
2148        int user1 = TEST_DEFAULT_USER;
2149        int user2 = TEST_DEFAULT_USER + 1;
2150        setupUserProfiles(user2);
2151
2152        // Set up the internal data first.
2153        assertTrue(mWifiConfigManager.loadFromStore());
2154
2155        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2156        // user2 is unlocked and switched to foreground.
2157        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2158        mWifiConfigManager.handleUserSwitch(user2);
2159        // Ensure that the read was invoked.
2160        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2161                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2162    }
2163
2164    /**
2165     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2166     * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not
2167     * read until the user is unlocked.
2168     */
2169    public void testHandleUserSwitchWhenLocked() throws Exception {
2170        int user1 = TEST_DEFAULT_USER;
2171        int user2 = TEST_DEFAULT_USER + 1;
2172        setupUserProfiles(user2);
2173
2174        // Set up the internal data first.
2175        assertTrue(mWifiConfigManager.loadFromStore());
2176
2177        // user2 is locked and switched to foreground.
2178        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2179        mWifiConfigManager.handleUserSwitch(user2);
2180
2181        // Ensure that the read was not invoked.
2182        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2183                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2184
2185        // Now try unlocking some other user (user1), this should be ignored.
2186        mWifiConfigManager.handleUserUnlock(user1);
2187        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2188                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2189
2190        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2191        // Unlock the user2 and ensure that we read the data now.
2192        mWifiConfigManager.handleUserUnlock(user2);
2193        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2194                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2195    }
2196
2197    /**
2198     * Verifies that the foreground user stop using {@link WifiConfigManager#handleUserStop(int)}
2199     * and ensures that the store is written only when the foreground user is stopped.
2200     */
2201    @Test
2202    public void testHandleUserStop() throws Exception {
2203        int user1 = TEST_DEFAULT_USER;
2204        int user2 = TEST_DEFAULT_USER + 1;
2205        setupUserProfiles(user2);
2206
2207        // Try stopping background user2 first, this should not do anything.
2208        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2209        mWifiConfigManager.handleUserStop(user2);
2210        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2211                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2212
2213        // Now try stopping the foreground user1, this should trigger a write to store.
2214        mWifiConfigManager.handleUserStop(user1);
2215        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2216                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2217        mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
2218    }
2219
2220    /**
2221     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
2222     * results in a store read after bootup.
2223     */
2224    @Test
2225    public void testHandleUserUnlockAfterBootup() throws Exception {
2226        int user1 = TEST_DEFAULT_USER;
2227
2228        // Set up the internal data first.
2229        assertTrue(mWifiConfigManager.loadFromStore());
2230        mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
2231        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2232        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2233                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2234
2235        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2236        // Unlock the user1 (default user) for the first time and ensure that we read the data.
2237        mWifiConfigManager.handleUserUnlock(user1);
2238        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
2239        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2240                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2241        mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
2242    }
2243
2244    /**
2245     * Verifies that the store read after bootup received after
2246     * foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
2247     * results in a user store read.
2248     */
2249    @Test
2250    public void testHandleBootupAfterUserUnlock() throws Exception {
2251        int user1 = TEST_DEFAULT_USER;
2252
2253        // Unlock the user1 (default user) for the first time and ensure that we don't read the
2254        // data.
2255        mWifiConfigManager.handleUserUnlock(user1);
2256        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
2257        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2258        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2259                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2260
2261        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2262        // Read from store now.
2263        assertTrue(mWifiConfigManager.loadFromStore());
2264        mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
2265        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2266                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2267        mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
2268    }
2269
2270    /**
2271     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} does
2272     * not always result in a store read unless the user had switched or just booted up.
2273     */
2274    @Test
2275    public void testHandleUserUnlockWithoutSwitchOrBootup() throws Exception {
2276        int user1 = TEST_DEFAULT_USER;
2277        int user2 = TEST_DEFAULT_USER + 1;
2278        setupUserProfiles(user2);
2279
2280        // Set up the internal data first.
2281        assertTrue(mWifiConfigManager.loadFromStore());
2282
2283        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2284        // user2 is unlocked and switched to foreground.
2285        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2286        mWifiConfigManager.handleUserSwitch(user2);
2287        // Ensure that the read was invoked.
2288        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2289                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2290
2291        // Unlock the user2 again and ensure that we don't read the data now.
2292        mWifiConfigManager.handleUserUnlock(user2);
2293        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2294                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2295    }
2296
2297    /**
2298     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserSwitch(int)}
2299     * is ignored if the legacy store migration is not complete.
2300     */
2301    @Test
2302    public void testHandleUserSwitchAfterBootupBeforeLegacyStoreMigration() throws Exception {
2303        int user2 = TEST_DEFAULT_USER + 1;
2304
2305        // Switch to user2 for the first time and ensure that we don't read or
2306        // write the store files.
2307        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2308        mWifiConfigManager.handleUserSwitch(user2);
2309        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2310                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2311        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2312    }
2313
2314    /**
2315     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
2316     * is ignored if the legacy store migration is not complete.
2317     */
2318    @Test
2319    public void testHandleUserUnlockAfterBootupBeforeLegacyStoreMigration() throws Exception {
2320        int user1 = TEST_DEFAULT_USER;
2321
2322        // Unlock the user1 (default user) for the first time and ensure that we don't read or
2323        // write the store files.
2324        mWifiConfigManager.handleUserUnlock(user1);
2325        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2326                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2327        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2328    }
2329
2330    /**
2331     * Verifies the private network addition using
2332     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
2333     * by a non foreground user is rejected.
2334     */
2335    @Test
2336    public void testAddNetworkUsingBackgroundUserUId() throws Exception {
2337        int user2 = TEST_DEFAULT_USER + 1;
2338        setupUserProfiles(user2);
2339
2340        int creatorUid = UserHandle.getUid(user2, 674);
2341
2342        // Create a network for user2 try adding it. This should be rejected.
2343        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2344        NetworkUpdateResult result =
2345                mWifiConfigManager.addOrUpdateNetwork(user2Network, creatorUid);
2346        assertFalse(result.isSuccess());
2347    }
2348
2349    /**
2350     * Verifies the private network addition using
2351     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
2352     * by SysUI is always accepted.
2353     */
2354    @Test
2355    public void testAddNetworkUsingSysUiUid() throws Exception {
2356        // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile|
2357        int user2 = TEST_DEFAULT_USER + 1;
2358        setupUserProfiles(user2);
2359
2360        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2361        mWifiConfigManager.handleUserSwitch(user2);
2362
2363        // Create a network for user2 try adding it. This should be rejected.
2364        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2365        NetworkUpdateResult result =
2366                mWifiConfigManager.addOrUpdateNetwork(user2Network, TEST_SYSUI_UID);
2367        assertTrue(result.isSuccess());
2368    }
2369
2370    /**
2371     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
2372     * attempts to migrate data from legacy stores when the legacy store files are present.
2373     */
2374    @Test
2375    public void testMigrationFromLegacyStore() throws Exception {
2376        // Create the store data to be returned from legacy stores.
2377        List<WifiConfiguration> networks = new ArrayList<>();
2378        networks.add(WifiConfigurationTestUtil.createPskNetwork());
2379        networks.add(WifiConfigurationTestUtil.createEapNetwork());
2380        networks.add(WifiConfigurationTestUtil.createWepNetwork());
2381        String deletedEphemeralSSID = "EphemeralSSID";
2382        Set<String> deletedEphermalSSIDs = new HashSet<>(Arrays.asList(deletedEphemeralSSID));
2383        WifiConfigStoreDataLegacy storeData =
2384                new WifiConfigStoreDataLegacy(networks, deletedEphermalSSIDs);
2385
2386        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true);
2387        when(mWifiConfigStoreLegacy.read()).thenReturn(storeData);
2388
2389        // Now trigger the migration from legacy store. This should populate the in memory list with
2390        // all the networks above from the legacy store.
2391        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
2392
2393        verify(mWifiConfigStoreLegacy).read();
2394        verify(mWifiConfigStoreLegacy).removeStores();
2395
2396        List<WifiConfiguration> retrievedNetworks =
2397                mWifiConfigManager.getConfiguredNetworksWithPasswords();
2398        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2399                networks, retrievedNetworks);
2400        assertTrue(mWifiConfigManager.wasEphemeralNetworkDeleted(deletedEphemeralSSID));
2401    }
2402
2403    /**
2404     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
2405     * does not attempt to migrate data from legacy stores when the legacy store files are absent
2406     * (i.e migration was already done once).
2407     */
2408    @Test
2409    public void testNoDuplicateMigrationFromLegacyStore() throws Exception {
2410        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
2411
2412        // Now trigger a migration from legacy store.
2413        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
2414
2415        verify(mWifiConfigStoreLegacy, never()).read();
2416        verify(mWifiConfigStoreLegacy, never()).removeStores();
2417    }
2418
2419    /**
2420     * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does
2421     * not attempt to read from any of the stores (new or legacy) when the store files are
2422     * not present.
2423     */
2424    @Test
2425    public void testFreshInstallDoesNotLoadFromStore() throws Exception {
2426        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
2427        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
2428
2429        assertTrue(mWifiConfigManager.loadFromStore());
2430
2431        verify(mWifiConfigStore, never()).read();
2432        verify(mWifiConfigStoreLegacy, never()).read();
2433
2434        assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
2435    }
2436
2437    /**
2438     * Verifies the user switch using {@link WifiConfigManager#handleUserSwitch(int)} is handled
2439     * when the store files (new or legacy) are not present.
2440     */
2441    @Test
2442    public void testHandleUserSwitchAfterFreshInstall() throws Exception {
2443        int user2 = TEST_DEFAULT_USER + 1;
2444        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
2445        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
2446
2447        assertTrue(mWifiConfigManager.loadFromStore());
2448        verify(mWifiConfigStore, never()).read();
2449        verify(mWifiConfigStoreLegacy, never()).read();
2450
2451        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2452        // Now switch the user to user 2.
2453        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2454        mWifiConfigManager.handleUserSwitch(user2);
2455        // Ensure that the read was invoked.
2456        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2457                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2458    }
2459
2460    /**
2461     * Verifies that the last user selected network parameter is set when
2462     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set
2463     * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or
2464     * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID.
2465     */
2466    @Test
2467    public void testLastSelectedNetwork() throws Exception {
2468        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
2469        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
2470
2471        when(mClock.getElapsedSinceBootMillis()).thenReturn(67L);
2472        assertTrue(mWifiConfigManager.enableNetwork(
2473                result.getNetworkId(), true, TEST_CREATOR_UID));
2474        assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
2475        assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp());
2476
2477        // Now disable the network and ensure that the last selected flag is cleared.
2478        assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID));
2479        assertEquals(
2480                WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
2481
2482        // Enable it again and remove the network to ensure that the last selected flag was cleared.
2483        assertTrue(mWifiConfigManager.enableNetwork(
2484                result.getNetworkId(), true, TEST_CREATOR_UID));
2485        assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
2486        assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey());
2487
2488        assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID));
2489        assertEquals(
2490                WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
2491    }
2492
2493    /**
2494     * Verifies that all the networks for the provided app is removed when
2495     * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked.
2496     */
2497    @Test
2498    public void testRemoveNetworksForApp() throws Exception {
2499        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
2500        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
2501        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
2502
2503        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2504
2505        ApplicationInfo app = new ApplicationInfo();
2506        app.uid = TEST_CREATOR_UID;
2507        app.packageName = TEST_CREATOR_NAME;
2508        assertEquals(3, mWifiConfigManager.removeNetworksForApp(app).size());
2509
2510        // Ensure all the networks are removed now.
2511        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2512    }
2513
2514    /**
2515     * Verifies that all the networks for the provided user is removed when
2516     * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked.
2517     */
2518    @Test
2519    public void testRemoveNetworksForUser() throws Exception {
2520        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
2521        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
2522        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
2523
2524        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2525
2526        assertEquals(3, mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER).size());
2527
2528        // Ensure all the networks are removed now.
2529        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2530    }
2531
2532    /**
2533     * Verifies that the connect choice is removed from all networks when
2534     * {@link WifiConfigManager#removeNetwork(int, int)} is invoked.
2535     */
2536    @Test
2537    public void testRemoveNetworkRemovesConnectChoice() throws Exception {
2538        WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
2539        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2540        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
2541        verifyAddNetworkToWifiConfigManager(network1);
2542        verifyAddNetworkToWifiConfigManager(network2);
2543        verifyAddNetworkToWifiConfigManager(network3);
2544
2545        // Set connect choice of network 2 over network 1.
2546        assertTrue(
2547                mWifiConfigManager.setNetworkConnectChoice(
2548                        network1.networkId, network2.configKey(), 78L));
2549
2550        WifiConfiguration retrievedNetwork =
2551                mWifiConfigManager.getConfiguredNetwork(network1.networkId);
2552        assertEquals(
2553                network2.configKey(),
2554                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
2555
2556        // Remove network 3 and ensure that the connect choice on network 1 is not removed.
2557        assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID));
2558        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
2559        assertEquals(
2560                network2.configKey(),
2561                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
2562
2563        // Now remove network 2 and ensure that the connect choice on network 1 is removed..
2564        assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID));
2565        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
2566        assertNotEquals(
2567                network2.configKey(),
2568                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
2569
2570        // This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for
2571        // clearing it after network removal.
2572        mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(eq(false));
2573    }
2574
2575    /**
2576     * Verifies that the modification of a single network using
2577     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any
2578     * updates to the network config in
2579     * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected
2580     * in the internal database.
2581     */
2582    @Test
2583    public void testUpdateSingleNetworkWithKeysUpdate() {
2584        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
2585        network.enterpriseConfig =
2586                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
2587        verifyAddNetworkToWifiConfigManager(network);
2588
2589        // Now verify that network configurations match before we make any change.
2590        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2591                network,
2592                mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
2593
2594        // Modify the network ca_cert field in updateNetworkKeys method during a network
2595        // config update.
2596        final String newCaCertAlias = "test";
2597        assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias());
2598
2599        doAnswer(new AnswerWithArguments() {
2600            public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) {
2601                newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
2602                return true;
2603            }
2604        }).when(mWifiKeyStore).updateNetworkKeys(
2605                any(WifiConfiguration.class), any(WifiConfiguration.class));
2606
2607        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
2608
2609        // Now verify that the keys update is reflected in the configuration fetched from internal
2610        // db.
2611        network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
2612        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2613                network,
2614                mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
2615    }
2616
2617    /**
2618     * Verifies that the dump method prints out all the saved network details with passwords masked.
2619     * {@link WifiConfigManager#dump(FileDescriptor, PrintWriter, String[])}.
2620     */
2621    @Test
2622    public void testDump() {
2623        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2624        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
2625        eapNetwork.enterpriseConfig.setPassword("blah");
2626
2627        verifyAddNetworkToWifiConfigManager(pskNetwork);
2628        verifyAddNetworkToWifiConfigManager(eapNetwork);
2629
2630        StringWriter stringWriter = new StringWriter();
2631        mWifiConfigManager.dump(
2632                new FileDescriptor(), new PrintWriter(stringWriter), new String[0]);
2633        String dumpString = stringWriter.toString();
2634
2635        // Ensure that the network SSIDs were dumped out.
2636        assertTrue(dumpString.contains(pskNetwork.SSID));
2637        assertTrue(dumpString.contains(eapNetwork.SSID));
2638
2639        // Ensure that the network passwords were not dumped out.
2640        assertFalse(dumpString.contains(pskNetwork.preSharedKey));
2641        assertFalse(dumpString.contains(eapNetwork.enterpriseConfig.getPassword()));
2642    }
2643
2644    /**
2645     * Verifies the ordering of network list generated using
2646     * {@link WifiConfigManager#retrieveHiddenNetworkList()}.
2647     */
2648    @Test
2649    public void testRetrieveHiddenList() {
2650        // Create and add 3 networks.
2651        WifiConfiguration network1 = WifiConfigurationTestUtil.createWepHiddenNetwork();
2652        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskHiddenNetwork();
2653        WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2654        verifyAddNetworkToWifiConfigManager(network1);
2655        verifyAddNetworkToWifiConfigManager(network2);
2656        verifyAddNetworkToWifiConfigManager(network3);
2657
2658        // Enable all of them.
2659        assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID));
2660        assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID));
2661        assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID));
2662
2663        // Now set scan results in 2 of them to set the corresponding
2664        // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field.
2665        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
2666                network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54));
2667        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
2668                network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54));
2669
2670        // Now increment |network3|'s association count. This should ensure that this network
2671        // is preferred over |network1|.
2672        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId));
2673
2674        // Retrieve the hidden network list & verify the order of the networks returned.
2675        List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks =
2676                mWifiConfigManager.retrieveHiddenNetworkList();
2677        assertEquals(3, hiddenNetworks.size());
2678        assertEquals(network3.SSID, hiddenNetworks.get(0).ssid);
2679        assertEquals(network1.SSID, hiddenNetworks.get(1).ssid);
2680        assertEquals(network2.SSID, hiddenNetworks.get(2).ssid);
2681
2682        // Now permanently disable |network3|. This should remove network 3 from the list.
2683        assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID));
2684
2685        // Retrieve the hidden network list again & verify the order of the networks returned.
2686        hiddenNetworks = mWifiConfigManager.retrieveHiddenNetworkList();
2687        assertEquals(2, hiddenNetworks.size());
2688        assertEquals(network1.SSID, hiddenNetworks.get(0).ssid);
2689        assertEquals(network2.SSID, hiddenNetworks.get(1).ssid);
2690    }
2691
2692    /**
2693     * Verifies the addition of network configurations using
2694     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and
2695     * default key mgmt does not add duplicate network configs.
2696     */
2697    @Test
2698    public void testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt() {
2699        final String ssid = "test_blah";
2700        // Add a network with the above SSID and default key mgmt and ensure it was added
2701        // successfully.
2702        WifiConfiguration network1 = new WifiConfiguration();
2703        network1.SSID = ssid;
2704        NetworkUpdateResult result = addNetworkToWifiConfigManager(network1);
2705        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2706        assertTrue(result.isNewNetwork());
2707
2708        List<WifiConfiguration> retrievedNetworks =
2709                mWifiConfigManager.getConfiguredNetworksWithPasswords();
2710        assertEquals(1, retrievedNetworks.size());
2711        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2712                network1, retrievedNetworks.get(0));
2713
2714        // Now add a second network with the same SSID and default key mgmt and ensure that it
2715        // didn't add a new duplicate network.
2716        WifiConfiguration network2 = new WifiConfiguration();
2717        network2.SSID = ssid;
2718        result = addNetworkToWifiConfigManager(network2);
2719        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2720        assertFalse(result.isNewNetwork());
2721
2722        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
2723        assertEquals(1, retrievedNetworks.size());
2724        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2725                network2, retrievedNetworks.get(0));
2726    }
2727
2728    /**
2729     * Verifies the addition of network configurations using
2730     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and
2731     * different key mgmt should add different network configs.
2732     */
2733    @Test
2734    public void testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt() {
2735        final String ssid = "test_blah";
2736        // Add a network with the above SSID and WPA_PSK key mgmt and ensure it was added
2737        // successfully.
2738        WifiConfiguration network1 = new WifiConfiguration();
2739        network1.SSID = ssid;
2740        network1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
2741        NetworkUpdateResult result = addNetworkToWifiConfigManager(network1);
2742        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2743        assertTrue(result.isNewNetwork());
2744
2745        List<WifiConfiguration> retrievedNetworks =
2746                mWifiConfigManager.getConfiguredNetworksWithPasswords();
2747        assertEquals(1, retrievedNetworks.size());
2748        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2749                network1, retrievedNetworks.get(0));
2750
2751        // Now add a second network with the same SSID and NONE key mgmt and ensure that it
2752        // does add a new network.
2753        WifiConfiguration network2 = new WifiConfiguration();
2754        network2.SSID = ssid;
2755        network2.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
2756        result = addNetworkToWifiConfigManager(network2);
2757        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2758        assertTrue(result.isNewNetwork());
2759
2760        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
2761        assertEquals(2, retrievedNetworks.size());
2762        List<WifiConfiguration> networks = Arrays.asList(network1, network2);
2763        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2764                networks, retrievedNetworks);
2765    }
2766
2767    /**
2768     * Verifies that adding a network with a proxy, without having permission OVERRIDE_WIFI_CONFIG,
2769     * holding device policy, or profile owner policy fails.
2770     */
2771    @Test
2772    public void testAddNetworkWithProxyFails() {
2773        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2774                false, // withConfOverride
2775                false, // withProfileOwnerPolicy
2776                false, // withDeviceOwnerPolicy
2777                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2778                false, // assertSuccess
2779                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2780        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2781                false, // withConfOverride
2782                false, // withProfileOwnerPolicy
2783                false, // withDeviceOwnerPolicy
2784                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2785                false, // assertSuccess
2786                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2787    }
2788
2789    /**
2790     * Verifies that adding a network with a PAC or STATIC proxy with permission
2791     * OVERRIDE_WIFI_CONFIG is successful
2792     */
2793    @Test
2794    public void testAddNetworkWithProxyWithConfOverride() {
2795        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2796                true,  // withConfOverride
2797                false, // withProfileOwnerPolicy
2798                false, // withDeviceOwnerPolicy
2799                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2800                true, // assertSuccess
2801                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2802        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2803                true,  // withConfOverride
2804                false, // withProfileOwnerPolicy
2805                false, // withDeviceOwnerPolicy
2806                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2807                true, // assertSuccess
2808                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2809    }
2810
2811    /**
2812     * Verifies that adding a network with a PAC or STATIC proxy, while holding policy
2813     * {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER} is successful
2814     */
2815    @Test
2816    public void testAddNetworkWithProxyAsProfileOwner() {
2817        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2818                false,  // withConfOverride
2819                true, // withProfileOwnerPolicy
2820                false, // withDeviceOwnerPolicy
2821                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2822                true, // assertSuccess
2823                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2824        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2825                false,  // withConfOverride
2826                true, // withProfileOwnerPolicy
2827                false, // withDeviceOwnerPolicy
2828                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2829                true, // assertSuccess
2830                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2831    }
2832    /**
2833     * Verifies that adding a network with a PAC or STATIC proxy, while holding policy
2834     * {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER} is successful
2835     */
2836    @Test
2837    public void testAddNetworkWithProxyAsDeviceOwner() {
2838        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2839                false,  // withConfOverride
2840                false, // withProfileOwnerPolicy
2841                true, // withDeviceOwnerPolicy
2842                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2843                true, // assertSuccess
2844                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2845        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2846                false,  // withConfOverride
2847                false, // withProfileOwnerPolicy
2848                true, // withDeviceOwnerPolicy
2849                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2850                true, // assertSuccess
2851                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2852    }
2853    /**
2854     * Verifies that updating a network (that has no proxy) and adding a PAC or STATIC proxy fails
2855     * without being able to override configs, or holding Device or Profile owner policies.
2856     */
2857    @Test
2858    public void testUpdateNetworkAddProxyFails() {
2859        WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2860        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
2861        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2862                false, // withConfOverride
2863                false, // withProfileOwnerPolicy
2864                false, // withDeviceOwnerPolicy
2865                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2866                false, // assertSuccess
2867                result.getNetworkId()); // Update networkID
2868        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2869                false, // withConfOverride
2870                false, // withProfileOwnerPolicy
2871                false, // withDeviceOwnerPolicy
2872                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2873                false, // assertSuccess
2874                result.getNetworkId()); // Update networkID
2875    }
2876    /**
2877     * Verifies that updating a network and adding a proxy is successful in the cases where app can
2878     * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
2879     * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
2880     * otherwise.
2881     */
2882    @Test
2883    public void testUpdateNetworkAddProxyWithPermissionAndSystem() {
2884        // Testing updating network with uid permission OVERRIDE_WIFI_CONFIG
2885        WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2886        NetworkUpdateResult result =
2887                mWifiConfigManager.addOrUpdateNetwork(network, TEST_CREATOR_UID);
2888        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2889        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2890                true, // withConfOverride
2891                false, // withProfileOwnerPolicy
2892                false, // withDeviceOwnerPolicy
2893                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2894                true, // assertSuccess
2895                result.getNetworkId()); // Update networkID
2896
2897        // Testing updating network with proxy while holding Profile Owner policy
2898        network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2899        result = mWifiConfigManager.addOrUpdateNetwork(network, TEST_NO_PERM_UID);
2900        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2901        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2902                false, // withConfOverride
2903                true, // withProfileOwnerPolicy
2904                false, // withDeviceOwnerPolicy
2905                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2906                true, // assertSuccess
2907                result.getNetworkId()); // Update networkID
2908
2909        // Testing updating network with proxy while holding Device Owner Policy
2910        network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2911        result = mWifiConfigManager.addOrUpdateNetwork(network, TEST_NO_PERM_UID);
2912        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2913        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2914                false, // withConfOverride
2915                false, // withProfileOwnerPolicy
2916                true, // withDeviceOwnerPolicy
2917                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2918                true, // assertSuccess
2919                result.getNetworkId()); // Update networkID
2920    }
2921
2922    /**
2923     * Verifies that updating a network that has a proxy without changing the proxy, can succeed
2924     * without proxy specific permissions.
2925     */
2926    @Test
2927    public void testUpdateNetworkUnchangedProxy() {
2928        IpConfiguration ipConf = WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy();
2929        // First create a WifiConfiguration with proxy
2930        NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2931                        false, // withConfOverride
2932                        true, // withProfileOwnerPolicy
2933                        false, // withDeviceOwnerPolicy
2934                        ipConf,
2935                        true, // assertSuccess
2936                        WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2937        // Update the network while using the same ipConf, and no proxy specific permissions
2938        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2939                        false, // withConfOverride
2940                        false, // withProfileOwnerPolicy
2941                        false, // withDeviceOwnerPolicy
2942                        ipConf,
2943                        true, // assertSuccess
2944                        result.getNetworkId()); // Update networkID
2945    }
2946
2947    /**
2948     * Verifies that updating a network with a different proxy succeeds in the cases where app can
2949     * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
2950     * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
2951     * otherwise.
2952     */
2953    @Test
2954    public void testUpdateNetworkDifferentProxy() {
2955        // Create two proxy configurations of the same type, but different values
2956        IpConfiguration ipConf1 =
2957                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
2958                        WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
2959                        TEST_STATIC_PROXY_HOST_1,
2960                        TEST_STATIC_PROXY_PORT_1,
2961                        TEST_STATIC_PROXY_EXCLUSION_LIST_1,
2962                        TEST_PAC_PROXY_LOCATION_1);
2963        IpConfiguration ipConf2 =
2964                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
2965                        WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
2966                        TEST_STATIC_PROXY_HOST_2,
2967                        TEST_STATIC_PROXY_PORT_2,
2968                        TEST_STATIC_PROXY_EXCLUSION_LIST_2,
2969                        TEST_PAC_PROXY_LOCATION_2);
2970
2971        // Update with Conf Override
2972        NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2973                true, // withConfOverride
2974                false, // withProfileOwnerPolicy
2975                false, // withDeviceOwnerPolicy
2976                ipConf1,
2977                true, // assertSuccess
2978                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2979        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2980                true, // withConfOverride
2981                false, // withProfileOwnerPolicy
2982                false, // withDeviceOwnerPolicy
2983                ipConf2,
2984                true, // assertSuccess
2985                result.getNetworkId()); // Update networkID
2986
2987        // Update as Device Owner
2988        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2989                false, // withConfOverride
2990                false, // withProfileOwnerPolicy
2991                true, // withDeviceOwnerPolicy
2992                ipConf1,
2993                true, // assertSuccess
2994                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2995        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2996                false, // withConfOverride
2997                false, // withProfileOwnerPolicy
2998                true, // withDeviceOwnerPolicy
2999                ipConf2,
3000                true, // assertSuccess
3001                result.getNetworkId()); // Update networkID
3002
3003        // Update as Profile Owner
3004        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3005                false, // withConfOverride
3006                true, // withProfileOwnerPolicy
3007                false, // withDeviceOwnerPolicy
3008                ipConf1,
3009                true, // assertSuccess
3010                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3011        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3012                false, // withConfOverride
3013                true, // withProfileOwnerPolicy
3014                false, // withDeviceOwnerPolicy
3015                ipConf2,
3016                true, // assertSuccess
3017                result.getNetworkId()); // Update networkID
3018
3019        // Update with no permissions (should fail)
3020        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3021                false, // withConfOverride
3022                true, // withProfileOwnerPolicy
3023                false, // withDeviceOwnerPolicy
3024                ipConf1,
3025                true, // assertSuccess
3026                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3027        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3028                false, // withConfOverride
3029                false, // withProfileOwnerPolicy
3030                false, // withDeviceOwnerPolicy
3031                ipConf2,
3032                false, // assertSuccess
3033                result.getNetworkId()); // Update networkID
3034    }
3035    /**
3036     * Verifies that updating a network removing its proxy succeeds in the cases where app can
3037     * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
3038     * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
3039     * otherwise.
3040     */
3041    @Test
3042    public void testUpdateNetworkRemoveProxy() {
3043        // Create two different IP configurations, one with a proxy and another without.
3044        IpConfiguration ipConf1 =
3045                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
3046                        WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
3047                        TEST_STATIC_PROXY_HOST_1,
3048                        TEST_STATIC_PROXY_PORT_1,
3049                        TEST_STATIC_PROXY_EXCLUSION_LIST_1,
3050                        TEST_PAC_PROXY_LOCATION_1);
3051        IpConfiguration ipConf2 =
3052                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
3053                        WifiConfigurationTestUtil.NONE_PROXY_SETTING,
3054                        TEST_STATIC_PROXY_HOST_2,
3055                        TEST_STATIC_PROXY_PORT_2,
3056                        TEST_STATIC_PROXY_EXCLUSION_LIST_2,
3057                        TEST_PAC_PROXY_LOCATION_2);
3058
3059        // Update with Conf Override
3060        NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3061                true, // withConfOverride
3062                false, // withProfileOwnerPolicy
3063                false, // withDeviceOwnerPolicy
3064                ipConf1,
3065                true, // assertSuccess
3066                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3067        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3068                true, // withConfOverride
3069                false, // withProfileOwnerPolicy
3070                false, // withDeviceOwnerPolicy
3071                ipConf2,
3072                true, // assertSuccess
3073                result.getNetworkId()); // Update networkID
3074
3075        // Update as Device Owner
3076        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3077                false, // withConfOverride
3078                false, // withProfileOwnerPolicy
3079                true, // withDeviceOwnerPolicy
3080                ipConf1,
3081                true, // assertSuccess
3082                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3083        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3084                false, // withConfOverride
3085                false, // withProfileOwnerPolicy
3086                true, // withDeviceOwnerPolicy
3087                ipConf2,
3088                true, // assertSuccess
3089                result.getNetworkId()); // Update networkID
3090
3091        // Update as Profile Owner
3092        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3093                false, // withConfOverride
3094                true, // withProfileOwnerPolicy
3095                false, // withDeviceOwnerPolicy
3096                ipConf1,
3097                true, // assertSuccess
3098                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3099        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3100                false, // withConfOverride
3101                true, // withProfileOwnerPolicy
3102                false, // withDeviceOwnerPolicy
3103                ipConf2,
3104                true, // assertSuccess
3105                result.getNetworkId()); // Update networkID
3106
3107        // Update with no permissions (should fail)
3108        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3109                false, // withConfOverride
3110                true, // withProfileOwnerPolicy
3111                false, // withDeviceOwnerPolicy
3112                ipConf1,
3113                true, // assertSuccess
3114                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3115        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3116                false, // withConfOverride
3117                false, // withProfileOwnerPolicy
3118                false, // withDeviceOwnerPolicy
3119                ipConf2,
3120                false, // assertSuccess
3121                result.getNetworkId()); // Update networkID
3122    }
3123
3124    private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3125            boolean withConfOverride,
3126            boolean withProfileOwnerPolicy,
3127            boolean withDeviceOwnerPolicy,
3128            IpConfiguration ipConfiguration,
3129            boolean assertSuccess,
3130            int networkId) {
3131        WifiConfiguration network;
3132        if (networkId == WifiConfiguration.INVALID_NETWORK_ID) {
3133            network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
3134        } else {
3135            network = mWifiConfigManager.getConfiguredNetwork(networkId);
3136        }
3137        network.setIpConfiguration(ipConfiguration);
3138        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(),
3139                eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER)))
3140                .thenReturn(withProfileOwnerPolicy);
3141        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(),
3142                eq(DeviceAdminInfo.USES_POLICY_DEVICE_OWNER)))
3143                .thenReturn(withDeviceOwnerPolicy);
3144        int uid = withConfOverride ? TEST_CREATOR_UID : TEST_NO_PERM_UID;
3145        NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(network, uid);
3146        assertEquals(assertSuccess, result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3147        return result;
3148    }
3149
3150    private void createWifiConfigManager() {
3151        mWifiConfigManager =
3152                new WifiConfigManager(
3153                        mContext, mFrameworkFacade, mClock, mUserManager, mTelephonyManager,
3154                        mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy,
3155                        mWifiPermissionsWrapper, mNetworkListStoreData,
3156                        mDeletedEphemeralSsidsStoreData);
3157        mWifiConfigManager.enableVerboseLogging(1);
3158    }
3159
3160    /**
3161     * This method sets defaults in the provided WifiConfiguration object if not set
3162     * so that it can be used for comparison with the configuration retrieved from
3163     * WifiConfigManager.
3164     */
3165    private void setDefaults(WifiConfiguration configuration) {
3166        if (configuration.allowedAuthAlgorithms.isEmpty()) {
3167            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
3168        }
3169        if (configuration.allowedProtocols.isEmpty()) {
3170            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
3171            configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
3172        }
3173        if (configuration.allowedKeyManagement.isEmpty()) {
3174            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
3175            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
3176        }
3177        if (configuration.allowedPairwiseCiphers.isEmpty()) {
3178            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
3179            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
3180        }
3181        if (configuration.allowedGroupCiphers.isEmpty()) {
3182            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
3183            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
3184            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
3185            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
3186        }
3187        if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) {
3188            configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
3189        }
3190        if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) {
3191            configuration.setProxySettings(IpConfiguration.ProxySettings.NONE);
3192        }
3193        configuration.status = WifiConfiguration.Status.DISABLED;
3194        configuration.getNetworkSelectionStatus().setNetworkSelectionStatus(
3195                NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED);
3196    }
3197
3198    /**
3199     * Modifies the provided configuration with creator uid, package name
3200     * and time.
3201     */
3202    private void setCreationDebugParams(WifiConfiguration configuration) {
3203        configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID;
3204        configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME;
3205        configuration.creationTime = configuration.updateTime =
3206                WifiConfigManager.createDebugTimeStampString(
3207                        TEST_WALLCLOCK_CREATION_TIME_MILLIS);
3208    }
3209
3210    /**
3211     * Modifies the provided configuration with update uid, package name
3212     * and time.
3213     */
3214    private void setUpdateDebugParams(WifiConfiguration configuration) {
3215        configuration.lastUpdateUid = TEST_UPDATE_UID;
3216        configuration.lastUpdateName = TEST_UPDATE_NAME;
3217        configuration.updateTime =
3218                WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
3219    }
3220
3221    private void assertNotEquals(Object expected, Object actual) {
3222        if (actual != null) {
3223            assertFalse(actual.equals(expected));
3224        } else {
3225            assertNotNull(expected);
3226        }
3227    }
3228
3229    /**
3230     * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that
3231     * the existing |BSSID| field is not the same value as the one being set
3232     */
3233    private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) {
3234        assertNotEquals(bssid, configuration.BSSID);
3235        configuration.BSSID = bssid;
3236    }
3237
3238    /**
3239     * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also,
3240     * asserts that the existing |mIpConfiguration| field is not the same value as the one being set
3241     */
3242    private void assertAndSetNetworkIpConfiguration(
3243            WifiConfiguration configuration, IpConfiguration ipConfiguration) {
3244        assertNotEquals(ipConfiguration, configuration.getIpConfiguration());
3245        configuration.setIpConfiguration(ipConfiguration);
3246    }
3247
3248    /**
3249     * Modifies the provided WifiConfiguration with the specified |wepKeys| value and
3250     * |wepTxKeyIndex|.
3251     */
3252    private void assertAndSetNetworkWepKeysAndTxIndex(
3253            WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) {
3254        assertNotEquals(wepKeys, configuration.wepKeys);
3255        assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex);
3256        configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length);
3257        configuration.wepTxKeyIndex = wepTxKeyIdx;
3258    }
3259
3260    /**
3261     * Modifies the provided WifiConfiguration with the specified |preSharedKey| value.
3262     */
3263    private void assertAndSetNetworkPreSharedKey(
3264            WifiConfiguration configuration, String preSharedKey) {
3265        assertNotEquals(preSharedKey, configuration.preSharedKey);
3266        configuration.preSharedKey = preSharedKey;
3267    }
3268
3269    /**
3270     * Modifies the provided WifiConfiguration with the specified enteprise |password| value.
3271     */
3272    private void assertAndSetNetworkEnterprisePassword(
3273            WifiConfiguration configuration, String password) {
3274        assertNotEquals(password, configuration.enterpriseConfig.getPassword());
3275        configuration.enterpriseConfig.setPassword(password);
3276    }
3277
3278    /**
3279     * Helper method to capture the networks list store data that will be written by
3280     * WifiConfigStore.write() method.
3281     */
3282    private Pair<List<WifiConfiguration>, List<WifiConfiguration>>
3283            captureWriteNetworksListStoreData() {
3284        try {
3285            ArgumentCaptor<ArrayList> sharedConfigsCaptor =
3286                    ArgumentCaptor.forClass(ArrayList.class);
3287            ArgumentCaptor<ArrayList> userConfigsCaptor =
3288                    ArgumentCaptor.forClass(ArrayList.class);
3289            mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData)
3290                    .setSharedConfigurations(sharedConfigsCaptor.capture());
3291            mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData)
3292                    .setUserConfigurations(userConfigsCaptor.capture());
3293            mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
3294            return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue());
3295        } catch (Exception e) {
3296            fail("Exception encountered during write " + e);
3297        }
3298        return null;
3299    }
3300
3301    /**
3302     * Returns whether the provided network was in the store data or not.
3303     */
3304    private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) {
3305        Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData =
3306                captureWriteNetworksListStoreData();
3307        if (networkListStoreData == null) {
3308            return false;
3309        }
3310        List<WifiConfiguration> networkList = new ArrayList<>();
3311        networkList.addAll(networkListStoreData.first);
3312        networkList.addAll(networkListStoreData.second);
3313        return isNetworkInConfigStoreData(configuration, networkList);
3314    }
3315
3316    /**
3317     * Returns whether the provided network was in the store data or not.
3318     */
3319    private boolean isNetworkInConfigStoreData(
3320            WifiConfiguration configuration, List<WifiConfiguration> networkList) {
3321        boolean foundNetworkInStoreData = false;
3322        for (WifiConfiguration retrievedConfig : networkList) {
3323            if (retrievedConfig.configKey().equals(configuration.configKey())) {
3324                foundNetworkInStoreData = true;
3325                break;
3326            }
3327        }
3328        return foundNetworkInStoreData;
3329    }
3330
3331    /**
3332     * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData
3333     * after WifiConfigStore#read.
3334     */
3335    private void setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations,
3336            List<WifiConfiguration> userConfigurations, Set<String> deletedEphemeralSsids) {
3337        when(mNetworkListStoreData.getSharedConfigurations())
3338                .thenReturn(sharedConfigurations);
3339        when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations);
3340        when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids);
3341    }
3342
3343    /**
3344     * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData
3345     * after WifiConfigStore#switchUserStoreAndRead.
3346     */
3347    private void setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations,
3348            Set<String> deletedEphemeralSsids) {
3349        when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations);
3350        when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids);
3351    }
3352
3353    /**
3354     * Verifies that the provided network was not present in the last config store write.
3355     */
3356    private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) {
3357        assertFalse(isNetworkInConfigStoreData(configuration));
3358    }
3359
3360    /**
3361     * Verifies that the provided network was present in the last config store write.
3362     */
3363    private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) {
3364        assertTrue(isNetworkInConfigStoreData(configuration));
3365    }
3366
3367    private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) {
3368        if (!TextUtils.isEmpty(configuration.preSharedKey)) {
3369            assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey);
3370        }
3371        if (configuration.wepKeys != null) {
3372            for (int i = 0; i < configuration.wepKeys.length; i++) {
3373                if (!TextUtils.isEmpty(configuration.wepKeys[i])) {
3374                    assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]);
3375                }
3376            }
3377        }
3378        if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) {
3379            assertEquals(
3380                    WifiConfigManager.PASSWORD_MASK,
3381                    configuration.enterpriseConfig.getPassword());
3382        }
3383    }
3384
3385    /**
3386     * Verifies that the network was present in the network change broadcast and returns the
3387     * change reason.
3388     */
3389    private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) {
3390        ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
3391        ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class);
3392        mContextConfigStoreMockOrder.verify(mContext)
3393                .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture());
3394
3395        assertEquals(userHandleCaptor.getValue(), UserHandle.ALL);
3396        Intent intent = intentCaptor.getValue();
3397
3398        int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1);
3399        WifiConfiguration retrievedConfig =
3400                (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION);
3401        assertEquals(retrievedConfig.configKey(), configuration.configKey());
3402
3403        // Verify that all the passwords are masked in the broadcast configuration.
3404        assertPasswordsMaskedInWifiConfiguration(retrievedConfig);
3405
3406        return changeReason;
3407    }
3408
3409    /**
3410     * Verifies that we sent out an add broadcast with the provided network.
3411     */
3412    private void verifyNetworkAddBroadcast(WifiConfiguration configuration) {
3413        assertEquals(
3414                verifyNetworkInBroadcastAndReturnReason(configuration),
3415                WifiManager.CHANGE_REASON_ADDED);
3416    }
3417
3418    /**
3419     * Verifies that we sent out an update broadcast with the provided network.
3420     */
3421    private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) {
3422        assertEquals(
3423                verifyNetworkInBroadcastAndReturnReason(configuration),
3424                WifiManager.CHANGE_REASON_CONFIG_CHANGE);
3425    }
3426
3427    /**
3428     * Verifies that we sent out a remove broadcast with the provided network.
3429     */
3430    private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) {
3431        assertEquals(
3432                verifyNetworkInBroadcastAndReturnReason(configuration),
3433                WifiManager.CHANGE_REASON_REMOVED);
3434    }
3435
3436    /**
3437     * Adds the provided configuration to WifiConfigManager and modifies the provided configuration
3438     * with creator/update uid, package name and time. This also sets defaults for fields not
3439     * populated.
3440     * These fields are populated internally by WifiConfigManager and hence we need
3441     * to modify the configuration before we compare the added network with the retrieved network.
3442     */
3443    private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) {
3444        when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS);
3445        NetworkUpdateResult result =
3446                mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_CREATOR_UID);
3447        setDefaults(configuration);
3448        setCreationDebugParams(configuration);
3449        configuration.networkId = result.getNetworkId();
3450        return result;
3451    }
3452
3453    /**
3454     * Add network to WifiConfigManager and ensure that it was successful.
3455     */
3456    private NetworkUpdateResult verifyAddNetworkToWifiConfigManager(
3457            WifiConfiguration configuration) {
3458        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
3459        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3460        assertTrue(result.isNewNetwork());
3461        assertTrue(result.hasIpChanged());
3462        assertTrue(result.hasProxyChanged());
3463
3464        verifyNetworkAddBroadcast(configuration);
3465        // Verify that the config store write was triggered with this new configuration.
3466        verifyNetworkInConfigStoreData(configuration);
3467        return result;
3468    }
3469
3470    /**
3471     * Add ephemeral network to WifiConfigManager and ensure that it was successful.
3472     */
3473    private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager(
3474            WifiConfiguration configuration) throws Exception {
3475        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
3476        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3477        assertTrue(result.isNewNetwork());
3478        assertTrue(result.hasIpChanged());
3479        assertTrue(result.hasProxyChanged());
3480
3481        verifyNetworkAddBroadcast(configuration);
3482        // Ensure that the write was not invoked for ephemeral network addition.
3483        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3484        return result;
3485    }
3486
3487    /**
3488     * Add Passpoint network to WifiConfigManager and ensure that it was successful.
3489     */
3490    private NetworkUpdateResult verifyAddPasspointNetworkToWifiConfigManager(
3491            WifiConfiguration configuration) throws Exception {
3492        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
3493        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3494        assertTrue(result.isNewNetwork());
3495        assertTrue(result.hasIpChanged());
3496        assertTrue(result.hasProxyChanged());
3497
3498        // Verify keys are not being installed.
3499        verify(mWifiKeyStore, never()).updateNetworkKeys(any(WifiConfiguration.class),
3500                any(WifiConfiguration.class));
3501        verifyNetworkAddBroadcast(configuration);
3502        // Ensure that the write was not invoked for Passpoint network addition.
3503        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3504        return result;
3505    }
3506
3507    /**
3508     * Updates the provided configuration to WifiConfigManager and modifies the provided
3509     * configuration with update uid, package name and time.
3510     * These fields are populated internally by WifiConfigManager and hence we need
3511     * to modify the configuration before we compare the added network with the retrieved network.
3512     */
3513    private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) {
3514        when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
3515        NetworkUpdateResult result =
3516                mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID);
3517        setUpdateDebugParams(configuration);
3518        return result;
3519    }
3520
3521    /**
3522     * Update network to WifiConfigManager config change and ensure that it was successful.
3523     */
3524    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager(
3525            WifiConfiguration configuration) {
3526        NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration);
3527        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3528        assertFalse(result.isNewNetwork());
3529
3530        verifyNetworkUpdateBroadcast(configuration);
3531        // Verify that the config store write was triggered with this new configuration.
3532        verifyNetworkInConfigStoreData(configuration);
3533        return result;
3534    }
3535
3536    /**
3537     * Update network to WifiConfigManager without IP config change and ensure that it was
3538     * successful.
3539     */
3540    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(
3541            WifiConfiguration configuration) {
3542        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
3543        assertFalse(result.hasIpChanged());
3544        assertFalse(result.hasProxyChanged());
3545        return result;
3546    }
3547
3548    /**
3549     * Update network to WifiConfigManager with IP config change and ensure that it was
3550     * successful.
3551     */
3552    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange(
3553            WifiConfiguration configuration) {
3554        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
3555        assertTrue(result.hasIpChanged());
3556        assertTrue(result.hasProxyChanged());
3557        return result;
3558    }
3559
3560    /**
3561     * Removes network from WifiConfigManager and ensure that it was successful.
3562     */
3563    private void verifyRemoveNetworkFromWifiConfigManager(
3564            WifiConfiguration configuration) {
3565        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
3566
3567        verifyNetworkRemoveBroadcast(configuration);
3568        // Verify if the config store write was triggered without this new configuration.
3569        verifyNetworkNotInConfigStoreData(configuration);
3570    }
3571
3572    /**
3573     * Removes ephemeral network from WifiConfigManager and ensure that it was successful.
3574     */
3575    private void verifyRemoveEphemeralNetworkFromWifiConfigManager(
3576            WifiConfiguration configuration) throws Exception {
3577        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
3578
3579        verifyNetworkRemoveBroadcast(configuration);
3580        // Ensure that the write was not invoked for ephemeral network remove.
3581        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3582    }
3583
3584    /**
3585     * Removes Passpoint network from WifiConfigManager and ensure that it was successful.
3586     */
3587    private void verifyRemovePasspointNetworkFromWifiConfigManager(
3588            WifiConfiguration configuration) throws Exception {
3589        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
3590
3591        // Verify keys are not being removed.
3592        verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class));
3593        verifyNetworkRemoveBroadcast(configuration);
3594        // Ensure that the write was not invoked for Passpoint network remove.
3595        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3596    }
3597
3598    /**
3599     * Verifies the provided network's public status and ensures that the network change broadcast
3600     * has been sent out.
3601     */
3602    private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) {
3603        assertEquals(status, configuration.status);
3604        verifyNetworkUpdateBroadcast(configuration);
3605    }
3606
3607    /**
3608     * Verifies the network's selection status update.
3609     *
3610     * For temporarily disabled reasons, the method ensures that the status has changed only if
3611     * disable reason counter has exceeded the threshold.
3612     *
3613     * For permanently disabled/enabled reasons, the method ensures that the public status has
3614     * changed and the network change broadcast has been sent out.
3615     */
3616    private void verifyUpdateNetworkSelectionStatus(
3617            int networkId, int reason, int temporaryDisableReasonCounter) {
3618        when(mClock.getElapsedSinceBootMillis())
3619                .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS);
3620
3621        // Fetch the current status of the network before we try to update the status.
3622        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
3623        NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus();
3624        int currentDisableReason = currentStatus.getNetworkSelectionDisableReason();
3625
3626        // First set the status to the provided reason.
3627        assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason));
3628
3629        // Now fetch the network configuration and verify the new status of the network.
3630        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
3631
3632        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
3633        int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason();
3634        long retrievedDisableTime = retrievedStatus.getDisableTime();
3635        int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason);
3636        int disableReasonThreshold =
3637                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason];
3638
3639        if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) {
3640            assertEquals(reason, retrievedDisableReason);
3641            assertTrue(retrievedStatus.isNetworkEnabled());
3642            assertEquals(
3643                    NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
3644                    retrievedDisableTime);
3645            verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
3646        } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) {
3647            // For temporarily disabled networks, we need to ensure that the current status remains
3648            // until the threshold is crossed.
3649            assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter);
3650            if (retrievedDisableReasonCounter < disableReasonThreshold) {
3651                assertEquals(currentDisableReason, retrievedDisableReason);
3652                assertEquals(
3653                        currentStatus.getNetworkSelectionStatus(),
3654                        retrievedStatus.getNetworkSelectionStatus());
3655            } else {
3656                assertEquals(reason, retrievedDisableReason);
3657                assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
3658                assertEquals(
3659                        TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime);
3660            }
3661        } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) {
3662            assertEquals(reason, retrievedDisableReason);
3663            assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
3664            assertEquals(
3665                    NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
3666                    retrievedDisableTime);
3667            verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
3668        }
3669    }
3670
3671    /**
3672     * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency
3673     * values.
3674     */
3675    private ScanDetail createScanDetailForNetwork(
3676            WifiConfiguration configuration, String bssid, int level, int frequency) {
3677        String caps;
3678        if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
3679            caps = "[WPA2-PSK-CCMP]";
3680        } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)
3681                || configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
3682            caps = "[WPA2-EAP-CCMP]";
3683        } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)
3684                && WifiConfigurationUtil.hasAnyValidWepKey(configuration.wepKeys)) {
3685            caps = "[WEP]";
3686        } else {
3687            caps = "[]";
3688        }
3689        WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid());
3690        // Fill in 0's in the fields we don't care about.
3691        return new ScanDetail(
3692                ssid, bssid, caps, level, frequency, mClock.getUptimeSinceBootMillis(),
3693                mClock.getWallClockMillis());
3694    }
3695
3696    /**
3697     * Creates a scan detail corresponding to the provided network and BSSID value.
3698     */
3699    private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) {
3700        return createScanDetailForNetwork(configuration, bssid, 0, 0);
3701    }
3702
3703    /**
3704     * Creates a scan detail corresponding to the provided network and fixed BSSID value.
3705     */
3706    private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) {
3707        return createScanDetailForNetwork(configuration, TEST_BSSID);
3708    }
3709
3710    /**
3711     * Adds the provided network and then creates a scan detail corresponding to the network. The
3712     * method then creates a ScanDetail corresponding to the network and ensures that the network
3713     * is properly matched using
3714     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} and also
3715     * verifies that the provided scan detail was cached,
3716     */
3717    private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
3718            WifiConfiguration network) {
3719        // First add the provided network.
3720        verifyAddNetworkToWifiConfigManager(network);
3721
3722        // Now create a dummy scan detail corresponding to the network.
3723        ScanDetail scanDetail = createScanDetailForNetwork(network);
3724        ScanResult scanResult = scanDetail.getScanResult();
3725
3726        WifiConfiguration retrievedNetwork =
3727                mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail);
3728        // Retrieve the network with password data for comparison.
3729        retrievedNetwork =
3730                mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId);
3731
3732        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3733                network, retrievedNetwork);
3734
3735        // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
3736        ScanDetailCache retrievedScanDetailCache =
3737                mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId);
3738        assertEquals(1, retrievedScanDetailCache.size());
3739        ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID);
3740
3741        ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
3742    }
3743
3744    /**
3745     * Adds a new network and verifies that the |HasEverConnected| flag is set to false.
3746     */
3747    private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) {
3748        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
3749        WifiConfiguration retrievedNetwork =
3750                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
3751        assertFalse("Adding a new network should not have hasEverConnected set to true.",
3752                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
3753    }
3754
3755    /**
3756     * Updates an existing network with some credential change and verifies that the
3757     * |HasEverConnected| flag is set to false.
3758     */
3759    private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(
3760            WifiConfiguration network) {
3761        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
3762        WifiConfiguration retrievedNetwork =
3763                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
3764        assertFalse("Updating network credentials config should clear hasEverConnected.",
3765                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
3766    }
3767
3768    /**
3769     * Updates an existing network after connection using
3770     * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the
3771     * |HasEverConnected| flag is set to true.
3772     */
3773    private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) {
3774        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId));
3775        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
3776        assertTrue("hasEverConnected expected to be true after connection.",
3777                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
3778    }
3779
3780    /**
3781     * Sets up a user profiles for WifiConfigManager testing.
3782     *
3783     * @param userId Id of the user.
3784     */
3785    private void setupUserProfiles(int userId) {
3786        final UserInfo userInfo =
3787                new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY);
3788        List<UserInfo> userProfiles = Arrays.asList(userInfo);
3789        when(mUserManager.getProfiles(userId)).thenReturn(userProfiles);
3790        when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true);
3791    }
3792
3793}
3794