WifiConfigManagerTest.java revision 040829fe448045d12cbc90f6143aca7da6b5aa80
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     * Verify that unlocking an user that owns a legacy Passpoint configuration (which is stored
2143     * temporarily in the share store) will migrate it to PasspointManager and removed from
2144     * the list of configured networks.
2145     *
2146     * @throws Exception
2147     */
2148    @Test
2149    public void testHandleUserUnlockRemovePasspointConfigFromSharedConfig() throws Exception {
2150        int user1 = TEST_DEFAULT_USER;
2151        int appId = 674;
2152
2153        final WifiConfiguration passpointConfig =
2154                WifiConfigurationTestUtil.createPasspointNetwork();
2155        passpointConfig.creatorUid = UserHandle.getUid(user1, appId);
2156
2157        // Set up the shared store data to contain one legacy Passpoint configuration.
2158        List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
2159            {
2160                add(passpointConfig);
2161            }
2162        };
2163        setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(),
2164                new HashSet<String>());
2165        assertTrue(mWifiConfigManager.loadFromStore());
2166        verify(mWifiConfigStore).read();
2167        assertEquals(1, mWifiConfigManager.getConfiguredNetworks().size());
2168
2169        // Unlock the owner of the legacy Passpoint configuration, verify it is removed from
2170        // the configured networks (migrated to PasspointManager).
2171        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2172        mWifiConfigManager.handleUserUnlock(user1);
2173        verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2174        Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList =
2175                captureWriteNetworksListStoreData();
2176        assertTrue(writtenNetworkList.first.isEmpty());
2177        assertTrue(writtenNetworkList.second.isEmpty());
2178        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2179    }
2180
2181    /**
2182     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2183     * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is
2184     * read immediately if the user is unlocked during the switch.
2185     */
2186    @Test
2187    public void testHandleUserSwitchWhenUnlocked() throws Exception {
2188        int user1 = TEST_DEFAULT_USER;
2189        int user2 = TEST_DEFAULT_USER + 1;
2190        setupUserProfiles(user2);
2191
2192        // Set up the internal data first.
2193        assertTrue(mWifiConfigManager.loadFromStore());
2194
2195        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2196        // user2 is unlocked and switched to foreground.
2197        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2198        mWifiConfigManager.handleUserSwitch(user2);
2199        // Ensure that the read was invoked.
2200        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2201                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2202    }
2203
2204    /**
2205     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2206     * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not
2207     * read until the user is unlocked.
2208     */
2209    public void testHandleUserSwitchWhenLocked() throws Exception {
2210        int user1 = TEST_DEFAULT_USER;
2211        int user2 = TEST_DEFAULT_USER + 1;
2212        setupUserProfiles(user2);
2213
2214        // Set up the internal data first.
2215        assertTrue(mWifiConfigManager.loadFromStore());
2216
2217        // user2 is locked and switched to foreground.
2218        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2219        mWifiConfigManager.handleUserSwitch(user2);
2220
2221        // Ensure that the read was not invoked.
2222        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2223                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2224
2225        // Now try unlocking some other user (user1), this should be ignored.
2226        mWifiConfigManager.handleUserUnlock(user1);
2227        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2228                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2229
2230        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2231        // Unlock the user2 and ensure that we read the data now.
2232        mWifiConfigManager.handleUserUnlock(user2);
2233        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2234                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2235    }
2236
2237    /**
2238     * Verifies that the foreground user stop using {@link WifiConfigManager#handleUserStop(int)}
2239     * and ensures that the store is written only when the foreground user is stopped.
2240     */
2241    @Test
2242    public void testHandleUserStop() throws Exception {
2243        int user1 = TEST_DEFAULT_USER;
2244        int user2 = TEST_DEFAULT_USER + 1;
2245        setupUserProfiles(user2);
2246
2247        // Try stopping background user2 first, this should not do anything.
2248        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2249        mWifiConfigManager.handleUserStop(user2);
2250        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2251                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2252
2253        // Now try stopping the foreground user1, this should trigger a write to store.
2254        mWifiConfigManager.handleUserStop(user1);
2255        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2256                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2257        mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
2258    }
2259
2260    /**
2261     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
2262     * results in a store read after bootup.
2263     */
2264    @Test
2265    public void testHandleUserUnlockAfterBootup() throws Exception {
2266        int user1 = TEST_DEFAULT_USER;
2267
2268        // Set up the internal data first.
2269        assertTrue(mWifiConfigManager.loadFromStore());
2270        mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
2271        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2272        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2273                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2274
2275        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2276        // Unlock the user1 (default user) for the first time and ensure that we read the data.
2277        mWifiConfigManager.handleUserUnlock(user1);
2278        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
2279        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2280                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2281        mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
2282    }
2283
2284    /**
2285     * Verifies that the store read after bootup received after
2286     * foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
2287     * results in a user store read.
2288     */
2289    @Test
2290    public void testHandleBootupAfterUserUnlock() throws Exception {
2291        int user1 = TEST_DEFAULT_USER;
2292
2293        // Unlock the user1 (default user) for the first time and ensure that we don't read the
2294        // data.
2295        mWifiConfigManager.handleUserUnlock(user1);
2296        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
2297        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2298        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2299                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2300
2301        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2302        // Read from store now.
2303        assertTrue(mWifiConfigManager.loadFromStore());
2304        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2305                .setUserStore(any(WifiConfigStore.StoreFile.class));
2306        mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
2307    }
2308
2309    /**
2310     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} does
2311     * not always result in a store read unless the user had switched or just booted up.
2312     */
2313    @Test
2314    public void testHandleUserUnlockWithoutSwitchOrBootup() throws Exception {
2315        int user1 = TEST_DEFAULT_USER;
2316        int user2 = TEST_DEFAULT_USER + 1;
2317        setupUserProfiles(user2);
2318
2319        // Set up the internal data first.
2320        assertTrue(mWifiConfigManager.loadFromStore());
2321
2322        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2323        // user2 is unlocked and switched to foreground.
2324        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2325        mWifiConfigManager.handleUserSwitch(user2);
2326        // Ensure that the read was invoked.
2327        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2328                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2329
2330        // Unlock the user2 again and ensure that we don't read the data now.
2331        mWifiConfigManager.handleUserUnlock(user2);
2332        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2333                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2334    }
2335
2336    /**
2337     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserSwitch(int)}
2338     * is ignored if the legacy store migration is not complete.
2339     */
2340    @Test
2341    public void testHandleUserSwitchAfterBootupBeforeLegacyStoreMigration() throws Exception {
2342        int user2 = TEST_DEFAULT_USER + 1;
2343
2344        // Switch to user2 for the first time and ensure that we don't read or
2345        // write the store files.
2346        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2347        mWifiConfigManager.handleUserSwitch(user2);
2348        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2349                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2350        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2351    }
2352
2353    /**
2354     * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
2355     * is ignored if the legacy store migration is not complete.
2356     */
2357    @Test
2358    public void testHandleUserUnlockAfterBootupBeforeLegacyStoreMigration() throws Exception {
2359        int user1 = TEST_DEFAULT_USER;
2360
2361        // Unlock the user1 (default user) for the first time and ensure that we don't read or
2362        // write the store files.
2363        mWifiConfigManager.handleUserUnlock(user1);
2364        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
2365                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2366        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
2367    }
2368
2369    /**
2370     * Verifies the private network addition using
2371     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
2372     * by a non foreground user is rejected.
2373     */
2374    @Test
2375    public void testAddNetworkUsingBackgroundUserUId() throws Exception {
2376        int user2 = TEST_DEFAULT_USER + 1;
2377        setupUserProfiles(user2);
2378
2379        int creatorUid = UserHandle.getUid(user2, 674);
2380
2381        // Create a network for user2 try adding it. This should be rejected.
2382        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2383        NetworkUpdateResult result =
2384                mWifiConfigManager.addOrUpdateNetwork(user2Network, creatorUid);
2385        assertFalse(result.isSuccess());
2386    }
2387
2388    /**
2389     * Verifies the private network addition using
2390     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
2391     * by SysUI is always accepted.
2392     */
2393    @Test
2394    public void testAddNetworkUsingSysUiUid() throws Exception {
2395        // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile|
2396        int user2 = TEST_DEFAULT_USER + 1;
2397        setupUserProfiles(user2);
2398
2399        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
2400        mWifiConfigManager.handleUserSwitch(user2);
2401
2402        // Create a network for user2 try adding it. This should be rejected.
2403        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2404        NetworkUpdateResult result =
2405                mWifiConfigManager.addOrUpdateNetwork(user2Network, TEST_SYSUI_UID);
2406        assertTrue(result.isSuccess());
2407    }
2408
2409    /**
2410     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
2411     * attempts to migrate data from legacy stores when the legacy store files are present.
2412     */
2413    @Test
2414    public void testMigrationFromLegacyStore() throws Exception {
2415        // Create the store data to be returned from legacy stores.
2416        List<WifiConfiguration> networks = new ArrayList<>();
2417        networks.add(WifiConfigurationTestUtil.createPskNetwork());
2418        networks.add(WifiConfigurationTestUtil.createEapNetwork());
2419        networks.add(WifiConfigurationTestUtil.createWepNetwork());
2420        String deletedEphemeralSSID = "EphemeralSSID";
2421        Set<String> deletedEphermalSSIDs = new HashSet<>(Arrays.asList(deletedEphemeralSSID));
2422        WifiConfigStoreDataLegacy storeData =
2423                new WifiConfigStoreDataLegacy(networks, deletedEphermalSSIDs);
2424
2425        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true);
2426        when(mWifiConfigStoreLegacy.read()).thenReturn(storeData);
2427
2428        // Now trigger the migration from legacy store. This should populate the in memory list with
2429        // all the networks above from the legacy store.
2430        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
2431
2432        verify(mWifiConfigStoreLegacy).read();
2433        verify(mWifiConfigStoreLegacy).removeStores();
2434
2435        List<WifiConfiguration> retrievedNetworks =
2436                mWifiConfigManager.getConfiguredNetworksWithPasswords();
2437        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2438                networks, retrievedNetworks);
2439        assertTrue(mWifiConfigManager.wasEphemeralNetworkDeleted(deletedEphemeralSSID));
2440    }
2441
2442    /**
2443     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
2444     * does not attempt to migrate data from legacy stores when the legacy store files are absent
2445     * (i.e migration was already done once).
2446     */
2447    @Test
2448    public void testNoDuplicateMigrationFromLegacyStore() throws Exception {
2449        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
2450
2451        // Now trigger a migration from legacy store.
2452        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
2453
2454        verify(mWifiConfigStoreLegacy, never()).read();
2455        verify(mWifiConfigStoreLegacy, never()).removeStores();
2456    }
2457
2458    /**
2459     * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does
2460     * not attempt to read from any of the stores (new or legacy) when the store files are
2461     * not present.
2462     */
2463    @Test
2464    public void testFreshInstallDoesNotLoadFromStore() throws Exception {
2465        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
2466        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
2467
2468        assertTrue(mWifiConfigManager.loadFromStore());
2469
2470        verify(mWifiConfigStore, never()).read();
2471        verify(mWifiConfigStoreLegacy, never()).read();
2472
2473        assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
2474    }
2475
2476    /**
2477     * Verifies the user switch using {@link WifiConfigManager#handleUserSwitch(int)} is handled
2478     * when the store files (new or legacy) are not present.
2479     */
2480    @Test
2481    public void testHandleUserSwitchAfterFreshInstall() throws Exception {
2482        int user2 = TEST_DEFAULT_USER + 1;
2483        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
2484        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
2485
2486        assertTrue(mWifiConfigManager.loadFromStore());
2487        verify(mWifiConfigStore, never()).read();
2488        verify(mWifiConfigStoreLegacy, never()).read();
2489
2490        setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
2491        // Now switch the user to user 2.
2492        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
2493        mWifiConfigManager.handleUserSwitch(user2);
2494        // Ensure that the read was invoked.
2495        mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2496                .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class));
2497    }
2498
2499    /**
2500     * Verifies that the last user selected network parameter is set when
2501     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set
2502     * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or
2503     * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID.
2504     */
2505    @Test
2506    public void testLastSelectedNetwork() throws Exception {
2507        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
2508        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
2509
2510        when(mClock.getElapsedSinceBootMillis()).thenReturn(67L);
2511        assertTrue(mWifiConfigManager.enableNetwork(
2512                result.getNetworkId(), true, TEST_CREATOR_UID));
2513        assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
2514        assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp());
2515
2516        // Now disable the network and ensure that the last selected flag is cleared.
2517        assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID));
2518        assertEquals(
2519                WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
2520
2521        // Enable it again and remove the network to ensure that the last selected flag was cleared.
2522        assertTrue(mWifiConfigManager.enableNetwork(
2523                result.getNetworkId(), true, TEST_CREATOR_UID));
2524        assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
2525        assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey());
2526
2527        assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID));
2528        assertEquals(
2529                WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
2530    }
2531
2532    /**
2533     * Verifies that all the networks for the provided app is removed when
2534     * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked.
2535     */
2536    @Test
2537    public void testRemoveNetworksForApp() throws Exception {
2538        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
2539        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
2540        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
2541
2542        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2543
2544        ApplicationInfo app = new ApplicationInfo();
2545        app.uid = TEST_CREATOR_UID;
2546        app.packageName = TEST_CREATOR_NAME;
2547        assertEquals(3, mWifiConfigManager.removeNetworksForApp(app).size());
2548
2549        // Ensure all the networks are removed now.
2550        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2551    }
2552
2553    /**
2554     * Verifies that all the networks for the provided user is removed when
2555     * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked.
2556     */
2557    @Test
2558    public void testRemoveNetworksForUser() throws Exception {
2559        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
2560        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
2561        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
2562
2563        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2564
2565        assertEquals(3, mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER).size());
2566
2567        // Ensure all the networks are removed now.
2568        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
2569    }
2570
2571    /**
2572     * Verifies that the connect choice is removed from all networks when
2573     * {@link WifiConfigManager#removeNetwork(int, int)} is invoked.
2574     */
2575    @Test
2576    public void testRemoveNetworkRemovesConnectChoice() throws Exception {
2577        WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
2578        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2579        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
2580        verifyAddNetworkToWifiConfigManager(network1);
2581        verifyAddNetworkToWifiConfigManager(network2);
2582        verifyAddNetworkToWifiConfigManager(network3);
2583
2584        // Set connect choice of network 2 over network 1.
2585        assertTrue(
2586                mWifiConfigManager.setNetworkConnectChoice(
2587                        network1.networkId, network2.configKey(), 78L));
2588
2589        WifiConfiguration retrievedNetwork =
2590                mWifiConfigManager.getConfiguredNetwork(network1.networkId);
2591        assertEquals(
2592                network2.configKey(),
2593                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
2594
2595        // Remove network 3 and ensure that the connect choice on network 1 is not removed.
2596        assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID));
2597        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
2598        assertEquals(
2599                network2.configKey(),
2600                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
2601
2602        // Now remove network 2 and ensure that the connect choice on network 1 is removed..
2603        assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID));
2604        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
2605        assertNotEquals(
2606                network2.configKey(),
2607                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
2608
2609        // This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for
2610        // clearing it after network removal.
2611        mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(eq(false));
2612    }
2613
2614    /**
2615     * Verifies that the modification of a single network using
2616     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any
2617     * updates to the network config in
2618     * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected
2619     * in the internal database.
2620     */
2621    @Test
2622    public void testUpdateSingleNetworkWithKeysUpdate() {
2623        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
2624        network.enterpriseConfig =
2625                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
2626        verifyAddNetworkToWifiConfigManager(network);
2627
2628        // Now verify that network configurations match before we make any change.
2629        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2630                network,
2631                mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
2632
2633        // Modify the network ca_cert field in updateNetworkKeys method during a network
2634        // config update.
2635        final String newCaCertAlias = "test";
2636        assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias());
2637
2638        doAnswer(new AnswerWithArguments() {
2639            public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) {
2640                newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
2641                return true;
2642            }
2643        }).when(mWifiKeyStore).updateNetworkKeys(
2644                any(WifiConfiguration.class), any(WifiConfiguration.class));
2645
2646        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
2647
2648        // Now verify that the keys update is reflected in the configuration fetched from internal
2649        // db.
2650        network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
2651        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2652                network,
2653                mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
2654    }
2655
2656    /**
2657     * Verifies that the dump method prints out all the saved network details with passwords masked.
2658     * {@link WifiConfigManager#dump(FileDescriptor, PrintWriter, String[])}.
2659     */
2660    @Test
2661    public void testDump() {
2662        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2663        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
2664        eapNetwork.enterpriseConfig.setPassword("blah");
2665
2666        verifyAddNetworkToWifiConfigManager(pskNetwork);
2667        verifyAddNetworkToWifiConfigManager(eapNetwork);
2668
2669        StringWriter stringWriter = new StringWriter();
2670        mWifiConfigManager.dump(
2671                new FileDescriptor(), new PrintWriter(stringWriter), new String[0]);
2672        String dumpString = stringWriter.toString();
2673
2674        // Ensure that the network SSIDs were dumped out.
2675        assertTrue(dumpString.contains(pskNetwork.SSID));
2676        assertTrue(dumpString.contains(eapNetwork.SSID));
2677
2678        // Ensure that the network passwords were not dumped out.
2679        assertFalse(dumpString.contains(pskNetwork.preSharedKey));
2680        assertFalse(dumpString.contains(eapNetwork.enterpriseConfig.getPassword()));
2681    }
2682
2683    /**
2684     * Verifies the ordering of network list generated using
2685     * {@link WifiConfigManager#retrieveHiddenNetworkList()}.
2686     */
2687    @Test
2688    public void testRetrieveHiddenList() {
2689        // Create and add 3 networks.
2690        WifiConfiguration network1 = WifiConfigurationTestUtil.createWepHiddenNetwork();
2691        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskHiddenNetwork();
2692        WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2693        verifyAddNetworkToWifiConfigManager(network1);
2694        verifyAddNetworkToWifiConfigManager(network2);
2695        verifyAddNetworkToWifiConfigManager(network3);
2696
2697        // Enable all of them.
2698        assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID));
2699        assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID));
2700        assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID));
2701
2702        // Now set scan results in 2 of them to set the corresponding
2703        // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field.
2704        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
2705                network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54));
2706        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
2707                network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54));
2708
2709        // Now increment |network3|'s association count. This should ensure that this network
2710        // is preferred over |network1|.
2711        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId));
2712
2713        // Retrieve the hidden network list & verify the order of the networks returned.
2714        List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks =
2715                mWifiConfigManager.retrieveHiddenNetworkList();
2716        assertEquals(3, hiddenNetworks.size());
2717        assertEquals(network3.SSID, hiddenNetworks.get(0).ssid);
2718        assertEquals(network1.SSID, hiddenNetworks.get(1).ssid);
2719        assertEquals(network2.SSID, hiddenNetworks.get(2).ssid);
2720
2721        // Now permanently disable |network3|. This should remove network 3 from the list.
2722        assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID));
2723
2724        // Retrieve the hidden network list again & verify the order of the networks returned.
2725        hiddenNetworks = mWifiConfigManager.retrieveHiddenNetworkList();
2726        assertEquals(2, hiddenNetworks.size());
2727        assertEquals(network1.SSID, hiddenNetworks.get(0).ssid);
2728        assertEquals(network2.SSID, hiddenNetworks.get(1).ssid);
2729    }
2730
2731    /**
2732     * Verifies the addition of network configurations using
2733     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and
2734     * default key mgmt does not add duplicate network configs.
2735     */
2736    @Test
2737    public void testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt() {
2738        final String ssid = "test_blah";
2739        // Add a network with the above SSID and default key mgmt and ensure it was added
2740        // successfully.
2741        WifiConfiguration network1 = new WifiConfiguration();
2742        network1.SSID = ssid;
2743        NetworkUpdateResult result = addNetworkToWifiConfigManager(network1);
2744        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2745        assertTrue(result.isNewNetwork());
2746
2747        List<WifiConfiguration> retrievedNetworks =
2748                mWifiConfigManager.getConfiguredNetworksWithPasswords();
2749        assertEquals(1, retrievedNetworks.size());
2750        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2751                network1, retrievedNetworks.get(0));
2752
2753        // Now add a second network with the same SSID and default key mgmt and ensure that it
2754        // didn't add a new duplicate network.
2755        WifiConfiguration network2 = new WifiConfiguration();
2756        network2.SSID = ssid;
2757        result = addNetworkToWifiConfigManager(network2);
2758        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2759        assertFalse(result.isNewNetwork());
2760
2761        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
2762        assertEquals(1, retrievedNetworks.size());
2763        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2764                network2, retrievedNetworks.get(0));
2765    }
2766
2767    /**
2768     * Verifies the addition of network configurations using
2769     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and
2770     * different key mgmt should add different network configs.
2771     */
2772    @Test
2773    public void testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt() {
2774        final String ssid = "test_blah";
2775        // Add a network with the above SSID and WPA_PSK key mgmt and ensure it was added
2776        // successfully.
2777        WifiConfiguration network1 = new WifiConfiguration();
2778        network1.SSID = ssid;
2779        network1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
2780        NetworkUpdateResult result = addNetworkToWifiConfigManager(network1);
2781        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2782        assertTrue(result.isNewNetwork());
2783
2784        List<WifiConfiguration> retrievedNetworks =
2785                mWifiConfigManager.getConfiguredNetworksWithPasswords();
2786        assertEquals(1, retrievedNetworks.size());
2787        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2788                network1, retrievedNetworks.get(0));
2789
2790        // Now add a second network with the same SSID and NONE key mgmt and ensure that it
2791        // does add a new network.
2792        WifiConfiguration network2 = new WifiConfiguration();
2793        network2.SSID = ssid;
2794        network2.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
2795        result = addNetworkToWifiConfigManager(network2);
2796        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2797        assertTrue(result.isNewNetwork());
2798
2799        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
2800        assertEquals(2, retrievedNetworks.size());
2801        List<WifiConfiguration> networks = Arrays.asList(network1, network2);
2802        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2803                networks, retrievedNetworks);
2804    }
2805
2806    /**
2807     * Verifies that adding a network with a proxy, without having permission OVERRIDE_WIFI_CONFIG,
2808     * holding device policy, or profile owner policy fails.
2809     */
2810    @Test
2811    public void testAddNetworkWithProxyFails() {
2812        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2813                false, // withConfOverride
2814                false, // withProfileOwnerPolicy
2815                false, // withDeviceOwnerPolicy
2816                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2817                false, // assertSuccess
2818                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2819        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2820                false, // withConfOverride
2821                false, // withProfileOwnerPolicy
2822                false, // withDeviceOwnerPolicy
2823                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2824                false, // assertSuccess
2825                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2826    }
2827
2828    /**
2829     * Verifies that adding a network with a PAC or STATIC proxy with permission
2830     * OVERRIDE_WIFI_CONFIG is successful
2831     */
2832    @Test
2833    public void testAddNetworkWithProxyWithConfOverride() {
2834        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2835                true,  // withConfOverride
2836                false, // withProfileOwnerPolicy
2837                false, // withDeviceOwnerPolicy
2838                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2839                true, // assertSuccess
2840                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2841        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2842                true,  // withConfOverride
2843                false, // withProfileOwnerPolicy
2844                false, // withDeviceOwnerPolicy
2845                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2846                true, // assertSuccess
2847                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2848    }
2849
2850    /**
2851     * Verifies that adding a network with a PAC or STATIC proxy, while holding policy
2852     * {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER} is successful
2853     */
2854    @Test
2855    public void testAddNetworkWithProxyAsProfileOwner() {
2856        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2857                false,  // withConfOverride
2858                true, // withProfileOwnerPolicy
2859                false, // withDeviceOwnerPolicy
2860                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2861                true, // assertSuccess
2862                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2863        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2864                false,  // withConfOverride
2865                true, // withProfileOwnerPolicy
2866                false, // withDeviceOwnerPolicy
2867                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2868                true, // assertSuccess
2869                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2870    }
2871    /**
2872     * Verifies that adding a network with a PAC or STATIC proxy, while holding policy
2873     * {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER} is successful
2874     */
2875    @Test
2876    public void testAddNetworkWithProxyAsDeviceOwner() {
2877        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2878                false,  // withConfOverride
2879                false, // withProfileOwnerPolicy
2880                true, // withDeviceOwnerPolicy
2881                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2882                true, // assertSuccess
2883                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2884        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2885                false,  // withConfOverride
2886                false, // withProfileOwnerPolicy
2887                true, // withDeviceOwnerPolicy
2888                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2889                true, // assertSuccess
2890                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2891    }
2892    /**
2893     * Verifies that updating a network (that has no proxy) and adding a PAC or STATIC proxy fails
2894     * without being able to override configs, or holding Device or Profile owner policies.
2895     */
2896    @Test
2897    public void testUpdateNetworkAddProxyFails() {
2898        WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2899        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
2900        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2901                false, // withConfOverride
2902                false, // withProfileOwnerPolicy
2903                false, // withDeviceOwnerPolicy
2904                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2905                false, // assertSuccess
2906                result.getNetworkId()); // Update networkID
2907        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2908                false, // withConfOverride
2909                false, // withProfileOwnerPolicy
2910                false, // withDeviceOwnerPolicy
2911                WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
2912                false, // assertSuccess
2913                result.getNetworkId()); // Update networkID
2914    }
2915    /**
2916     * Verifies that updating a network and adding a proxy is successful in the cases where app can
2917     * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
2918     * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
2919     * otherwise.
2920     */
2921    @Test
2922    public void testUpdateNetworkAddProxyWithPermissionAndSystem() {
2923        // Testing updating network with uid permission OVERRIDE_WIFI_CONFIG
2924        WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2925        NetworkUpdateResult result =
2926                mWifiConfigManager.addOrUpdateNetwork(network, TEST_CREATOR_UID);
2927        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2928        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2929                true, // withConfOverride
2930                false, // withProfileOwnerPolicy
2931                false, // withDeviceOwnerPolicy
2932                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2933                true, // assertSuccess
2934                result.getNetworkId()); // Update networkID
2935
2936        // Testing updating network with proxy while holding Profile Owner policy
2937        network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2938        result = mWifiConfigManager.addOrUpdateNetwork(network, TEST_NO_PERM_UID);
2939        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2940        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2941                false, // withConfOverride
2942                true, // withProfileOwnerPolicy
2943                false, // withDeviceOwnerPolicy
2944                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2945                true, // assertSuccess
2946                result.getNetworkId()); // Update networkID
2947
2948        // Testing updating network with proxy while holding Device Owner Policy
2949        network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
2950        result = mWifiConfigManager.addOrUpdateNetwork(network, TEST_NO_PERM_UID);
2951        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2952        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2953                false, // withConfOverride
2954                false, // withProfileOwnerPolicy
2955                true, // withDeviceOwnerPolicy
2956                WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
2957                true, // assertSuccess
2958                result.getNetworkId()); // Update networkID
2959    }
2960
2961    /**
2962     * Verifies that updating a network that has a proxy without changing the proxy, can succeed
2963     * without proxy specific permissions.
2964     */
2965    @Test
2966    public void testUpdateNetworkUnchangedProxy() {
2967        IpConfiguration ipConf = WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy();
2968        // First create a WifiConfiguration with proxy
2969        NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2970                        false, // withConfOverride
2971                        true, // withProfileOwnerPolicy
2972                        false, // withDeviceOwnerPolicy
2973                        ipConf,
2974                        true, // assertSuccess
2975                        WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
2976        // Update the network while using the same ipConf, and no proxy specific permissions
2977        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
2978                        false, // withConfOverride
2979                        false, // withProfileOwnerPolicy
2980                        false, // withDeviceOwnerPolicy
2981                        ipConf,
2982                        true, // assertSuccess
2983                        result.getNetworkId()); // Update networkID
2984    }
2985
2986    /**
2987     * Verifies that updating a network with a different proxy succeeds in the cases where app can
2988     * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
2989     * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
2990     * otherwise.
2991     */
2992    @Test
2993    public void testUpdateNetworkDifferentProxy() {
2994        // Create two proxy configurations of the same type, but different values
2995        IpConfiguration ipConf1 =
2996                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
2997                        WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
2998                        TEST_STATIC_PROXY_HOST_1,
2999                        TEST_STATIC_PROXY_PORT_1,
3000                        TEST_STATIC_PROXY_EXCLUSION_LIST_1,
3001                        TEST_PAC_PROXY_LOCATION_1);
3002        IpConfiguration ipConf2 =
3003                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
3004                        WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
3005                        TEST_STATIC_PROXY_HOST_2,
3006                        TEST_STATIC_PROXY_PORT_2,
3007                        TEST_STATIC_PROXY_EXCLUSION_LIST_2,
3008                        TEST_PAC_PROXY_LOCATION_2);
3009
3010        // Update with Conf Override
3011        NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3012                true, // withConfOverride
3013                false, // withProfileOwnerPolicy
3014                false, // withDeviceOwnerPolicy
3015                ipConf1,
3016                true, // assertSuccess
3017                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3018        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3019                true, // withConfOverride
3020                false, // withProfileOwnerPolicy
3021                false, // withDeviceOwnerPolicy
3022                ipConf2,
3023                true, // assertSuccess
3024                result.getNetworkId()); // Update networkID
3025
3026        // Update as Device Owner
3027        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3028                false, // withConfOverride
3029                false, // withProfileOwnerPolicy
3030                true, // withDeviceOwnerPolicy
3031                ipConf1,
3032                true, // assertSuccess
3033                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3034        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3035                false, // withConfOverride
3036                false, // withProfileOwnerPolicy
3037                true, // withDeviceOwnerPolicy
3038                ipConf2,
3039                true, // assertSuccess
3040                result.getNetworkId()); // Update networkID
3041
3042        // Update as Profile Owner
3043        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3044                false, // withConfOverride
3045                true, // withProfileOwnerPolicy
3046                false, // withDeviceOwnerPolicy
3047                ipConf1,
3048                true, // assertSuccess
3049                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3050        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3051                false, // withConfOverride
3052                true, // withProfileOwnerPolicy
3053                false, // withDeviceOwnerPolicy
3054                ipConf2,
3055                true, // assertSuccess
3056                result.getNetworkId()); // Update networkID
3057
3058        // Update with no permissions (should fail)
3059        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3060                false, // withConfOverride
3061                true, // withProfileOwnerPolicy
3062                false, // withDeviceOwnerPolicy
3063                ipConf1,
3064                true, // assertSuccess
3065                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3066        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3067                false, // withConfOverride
3068                false, // withProfileOwnerPolicy
3069                false, // withDeviceOwnerPolicy
3070                ipConf2,
3071                false, // assertSuccess
3072                result.getNetworkId()); // Update networkID
3073    }
3074    /**
3075     * Verifies that updating a network removing its proxy succeeds in the cases where app can
3076     * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
3077     * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
3078     * otherwise.
3079     */
3080    @Test
3081    public void testUpdateNetworkRemoveProxy() {
3082        // Create two different IP configurations, one with a proxy and another without.
3083        IpConfiguration ipConf1 =
3084                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
3085                        WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
3086                        TEST_STATIC_PROXY_HOST_1,
3087                        TEST_STATIC_PROXY_PORT_1,
3088                        TEST_STATIC_PROXY_EXCLUSION_LIST_1,
3089                        TEST_PAC_PROXY_LOCATION_1);
3090        IpConfiguration ipConf2 =
3091                WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
3092                        WifiConfigurationTestUtil.NONE_PROXY_SETTING,
3093                        TEST_STATIC_PROXY_HOST_2,
3094                        TEST_STATIC_PROXY_PORT_2,
3095                        TEST_STATIC_PROXY_EXCLUSION_LIST_2,
3096                        TEST_PAC_PROXY_LOCATION_2);
3097
3098        // Update with Conf Override
3099        NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3100                true, // withConfOverride
3101                false, // withProfileOwnerPolicy
3102                false, // withDeviceOwnerPolicy
3103                ipConf1,
3104                true, // assertSuccess
3105                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3106        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3107                true, // withConfOverride
3108                false, // withProfileOwnerPolicy
3109                false, // withDeviceOwnerPolicy
3110                ipConf2,
3111                true, // assertSuccess
3112                result.getNetworkId()); // Update networkID
3113
3114        // Update as Device Owner
3115        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3116                false, // withConfOverride
3117                false, // withProfileOwnerPolicy
3118                true, // withDeviceOwnerPolicy
3119                ipConf1,
3120                true, // assertSuccess
3121                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3122        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3123                false, // withConfOverride
3124                false, // withProfileOwnerPolicy
3125                true, // withDeviceOwnerPolicy
3126                ipConf2,
3127                true, // assertSuccess
3128                result.getNetworkId()); // Update networkID
3129
3130        // Update as Profile Owner
3131        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3132                false, // withConfOverride
3133                true, // withProfileOwnerPolicy
3134                false, // withDeviceOwnerPolicy
3135                ipConf1,
3136                true, // assertSuccess
3137                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3138        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3139                false, // withConfOverride
3140                true, // withProfileOwnerPolicy
3141                false, // withDeviceOwnerPolicy
3142                ipConf2,
3143                true, // assertSuccess
3144                result.getNetworkId()); // Update networkID
3145
3146        // Update with no permissions (should fail)
3147        result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3148                false, // withConfOverride
3149                true, // withProfileOwnerPolicy
3150                false, // withDeviceOwnerPolicy
3151                ipConf1,
3152                true, // assertSuccess
3153                WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3154        verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3155                false, // withConfOverride
3156                false, // withProfileOwnerPolicy
3157                false, // withDeviceOwnerPolicy
3158                ipConf2,
3159                false, // assertSuccess
3160                result.getNetworkId()); // Update networkID
3161    }
3162
3163    private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3164            boolean withConfOverride,
3165            boolean withProfileOwnerPolicy,
3166            boolean withDeviceOwnerPolicy,
3167            IpConfiguration ipConfiguration,
3168            boolean assertSuccess,
3169            int networkId) {
3170        WifiConfiguration network;
3171        if (networkId == WifiConfiguration.INVALID_NETWORK_ID) {
3172            network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
3173        } else {
3174            network = mWifiConfigManager.getConfiguredNetwork(networkId);
3175        }
3176        network.setIpConfiguration(ipConfiguration);
3177        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(),
3178                eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER)))
3179                .thenReturn(withProfileOwnerPolicy);
3180        when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(),
3181                eq(DeviceAdminInfo.USES_POLICY_DEVICE_OWNER)))
3182                .thenReturn(withDeviceOwnerPolicy);
3183        int uid = withConfOverride ? TEST_CREATOR_UID : TEST_NO_PERM_UID;
3184        NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(network, uid);
3185        assertEquals(assertSuccess, result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3186        return result;
3187    }
3188
3189    private void createWifiConfigManager() {
3190        mWifiConfigManager =
3191                new WifiConfigManager(
3192                        mContext, mFrameworkFacade, mClock, mUserManager, mTelephonyManager,
3193                        mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy,
3194                        mWifiPermissionsWrapper, mNetworkListStoreData,
3195                        mDeletedEphemeralSsidsStoreData);
3196        mWifiConfigManager.enableVerboseLogging(1);
3197    }
3198
3199    /**
3200     * This method sets defaults in the provided WifiConfiguration object if not set
3201     * so that it can be used for comparison with the configuration retrieved from
3202     * WifiConfigManager.
3203     */
3204    private void setDefaults(WifiConfiguration configuration) {
3205        if (configuration.allowedAuthAlgorithms.isEmpty()) {
3206            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
3207        }
3208        if (configuration.allowedProtocols.isEmpty()) {
3209            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
3210            configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
3211        }
3212        if (configuration.allowedKeyManagement.isEmpty()) {
3213            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
3214            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
3215        }
3216        if (configuration.allowedPairwiseCiphers.isEmpty()) {
3217            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
3218            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
3219        }
3220        if (configuration.allowedGroupCiphers.isEmpty()) {
3221            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
3222            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
3223            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
3224            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
3225        }
3226        if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) {
3227            configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
3228        }
3229        if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) {
3230            configuration.setProxySettings(IpConfiguration.ProxySettings.NONE);
3231        }
3232        configuration.status = WifiConfiguration.Status.DISABLED;
3233        configuration.getNetworkSelectionStatus().setNetworkSelectionStatus(
3234                NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED);
3235    }
3236
3237    /**
3238     * Modifies the provided configuration with creator uid, package name
3239     * and time.
3240     */
3241    private void setCreationDebugParams(WifiConfiguration configuration) {
3242        configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID;
3243        configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME;
3244        configuration.creationTime = configuration.updateTime =
3245                WifiConfigManager.createDebugTimeStampString(
3246                        TEST_WALLCLOCK_CREATION_TIME_MILLIS);
3247    }
3248
3249    /**
3250     * Modifies the provided configuration with update uid, package name
3251     * and time.
3252     */
3253    private void setUpdateDebugParams(WifiConfiguration configuration) {
3254        configuration.lastUpdateUid = TEST_UPDATE_UID;
3255        configuration.lastUpdateName = TEST_UPDATE_NAME;
3256        configuration.updateTime =
3257                WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
3258    }
3259
3260    private void assertNotEquals(Object expected, Object actual) {
3261        if (actual != null) {
3262            assertFalse(actual.equals(expected));
3263        } else {
3264            assertNotNull(expected);
3265        }
3266    }
3267
3268    /**
3269     * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that
3270     * the existing |BSSID| field is not the same value as the one being set
3271     */
3272    private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) {
3273        assertNotEquals(bssid, configuration.BSSID);
3274        configuration.BSSID = bssid;
3275    }
3276
3277    /**
3278     * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also,
3279     * asserts that the existing |mIpConfiguration| field is not the same value as the one being set
3280     */
3281    private void assertAndSetNetworkIpConfiguration(
3282            WifiConfiguration configuration, IpConfiguration ipConfiguration) {
3283        assertNotEquals(ipConfiguration, configuration.getIpConfiguration());
3284        configuration.setIpConfiguration(ipConfiguration);
3285    }
3286
3287    /**
3288     * Modifies the provided WifiConfiguration with the specified |wepKeys| value and
3289     * |wepTxKeyIndex|.
3290     */
3291    private void assertAndSetNetworkWepKeysAndTxIndex(
3292            WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) {
3293        assertNotEquals(wepKeys, configuration.wepKeys);
3294        assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex);
3295        configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length);
3296        configuration.wepTxKeyIndex = wepTxKeyIdx;
3297    }
3298
3299    /**
3300     * Modifies the provided WifiConfiguration with the specified |preSharedKey| value.
3301     */
3302    private void assertAndSetNetworkPreSharedKey(
3303            WifiConfiguration configuration, String preSharedKey) {
3304        assertNotEquals(preSharedKey, configuration.preSharedKey);
3305        configuration.preSharedKey = preSharedKey;
3306    }
3307
3308    /**
3309     * Modifies the provided WifiConfiguration with the specified enteprise |password| value.
3310     */
3311    private void assertAndSetNetworkEnterprisePassword(
3312            WifiConfiguration configuration, String password) {
3313        assertNotEquals(password, configuration.enterpriseConfig.getPassword());
3314        configuration.enterpriseConfig.setPassword(password);
3315    }
3316
3317    /**
3318     * Helper method to capture the networks list store data that will be written by
3319     * WifiConfigStore.write() method.
3320     */
3321    private Pair<List<WifiConfiguration>, List<WifiConfiguration>>
3322            captureWriteNetworksListStoreData() {
3323        try {
3324            ArgumentCaptor<ArrayList> sharedConfigsCaptor =
3325                    ArgumentCaptor.forClass(ArrayList.class);
3326            ArgumentCaptor<ArrayList> userConfigsCaptor =
3327                    ArgumentCaptor.forClass(ArrayList.class);
3328            mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData)
3329                    .setSharedConfigurations(sharedConfigsCaptor.capture());
3330            mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData)
3331                    .setUserConfigurations(userConfigsCaptor.capture());
3332            mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
3333            return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue());
3334        } catch (Exception e) {
3335            fail("Exception encountered during write " + e);
3336        }
3337        return null;
3338    }
3339
3340    /**
3341     * Returns whether the provided network was in the store data or not.
3342     */
3343    private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) {
3344        Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData =
3345                captureWriteNetworksListStoreData();
3346        if (networkListStoreData == null) {
3347            return false;
3348        }
3349        List<WifiConfiguration> networkList = new ArrayList<>();
3350        networkList.addAll(networkListStoreData.first);
3351        networkList.addAll(networkListStoreData.second);
3352        return isNetworkInConfigStoreData(configuration, networkList);
3353    }
3354
3355    /**
3356     * Returns whether the provided network was in the store data or not.
3357     */
3358    private boolean isNetworkInConfigStoreData(
3359            WifiConfiguration configuration, List<WifiConfiguration> networkList) {
3360        boolean foundNetworkInStoreData = false;
3361        for (WifiConfiguration retrievedConfig : networkList) {
3362            if (retrievedConfig.configKey().equals(configuration.configKey())) {
3363                foundNetworkInStoreData = true;
3364                break;
3365            }
3366        }
3367        return foundNetworkInStoreData;
3368    }
3369
3370    /**
3371     * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData
3372     * after WifiConfigStore#read.
3373     */
3374    private void setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations,
3375            List<WifiConfiguration> userConfigurations, Set<String> deletedEphemeralSsids) {
3376        when(mNetworkListStoreData.getSharedConfigurations())
3377                .thenReturn(sharedConfigurations);
3378        when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations);
3379        when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids);
3380    }
3381
3382    /**
3383     * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData
3384     * after WifiConfigStore#switchUserStoreAndRead.
3385     */
3386    private void setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations,
3387            Set<String> deletedEphemeralSsids) {
3388        when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations);
3389        when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids);
3390    }
3391
3392    /**
3393     * Verifies that the provided network was not present in the last config store write.
3394     */
3395    private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) {
3396        assertFalse(isNetworkInConfigStoreData(configuration));
3397    }
3398
3399    /**
3400     * Verifies that the provided network was present in the last config store write.
3401     */
3402    private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) {
3403        assertTrue(isNetworkInConfigStoreData(configuration));
3404    }
3405
3406    private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) {
3407        if (!TextUtils.isEmpty(configuration.preSharedKey)) {
3408            assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey);
3409        }
3410        if (configuration.wepKeys != null) {
3411            for (int i = 0; i < configuration.wepKeys.length; i++) {
3412                if (!TextUtils.isEmpty(configuration.wepKeys[i])) {
3413                    assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]);
3414                }
3415            }
3416        }
3417        if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) {
3418            assertEquals(
3419                    WifiConfigManager.PASSWORD_MASK,
3420                    configuration.enterpriseConfig.getPassword());
3421        }
3422    }
3423
3424    /**
3425     * Verifies that the network was present in the network change broadcast and returns the
3426     * change reason.
3427     */
3428    private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) {
3429        ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
3430        ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class);
3431        mContextConfigStoreMockOrder.verify(mContext)
3432                .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture());
3433
3434        assertEquals(userHandleCaptor.getValue(), UserHandle.ALL);
3435        Intent intent = intentCaptor.getValue();
3436
3437        int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1);
3438        WifiConfiguration retrievedConfig =
3439                (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION);
3440        assertEquals(retrievedConfig.configKey(), configuration.configKey());
3441
3442        // Verify that all the passwords are masked in the broadcast configuration.
3443        assertPasswordsMaskedInWifiConfiguration(retrievedConfig);
3444
3445        return changeReason;
3446    }
3447
3448    /**
3449     * Verifies that we sent out an add broadcast with the provided network.
3450     */
3451    private void verifyNetworkAddBroadcast(WifiConfiguration configuration) {
3452        assertEquals(
3453                verifyNetworkInBroadcastAndReturnReason(configuration),
3454                WifiManager.CHANGE_REASON_ADDED);
3455    }
3456
3457    /**
3458     * Verifies that we sent out an update broadcast with the provided network.
3459     */
3460    private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) {
3461        assertEquals(
3462                verifyNetworkInBroadcastAndReturnReason(configuration),
3463                WifiManager.CHANGE_REASON_CONFIG_CHANGE);
3464    }
3465
3466    /**
3467     * Verifies that we sent out a remove broadcast with the provided network.
3468     */
3469    private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) {
3470        assertEquals(
3471                verifyNetworkInBroadcastAndReturnReason(configuration),
3472                WifiManager.CHANGE_REASON_REMOVED);
3473    }
3474
3475    /**
3476     * Adds the provided configuration to WifiConfigManager and modifies the provided configuration
3477     * with creator/update uid, package name and time. This also sets defaults for fields not
3478     * populated.
3479     * These fields are populated internally by WifiConfigManager and hence we need
3480     * to modify the configuration before we compare the added network with the retrieved network.
3481     */
3482    private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) {
3483        when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS);
3484        NetworkUpdateResult result =
3485                mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_CREATOR_UID);
3486        setDefaults(configuration);
3487        setCreationDebugParams(configuration);
3488        configuration.networkId = result.getNetworkId();
3489        return result;
3490    }
3491
3492    /**
3493     * Add network to WifiConfigManager and ensure that it was successful.
3494     */
3495    private NetworkUpdateResult verifyAddNetworkToWifiConfigManager(
3496            WifiConfiguration configuration) {
3497        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
3498        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3499        assertTrue(result.isNewNetwork());
3500        assertTrue(result.hasIpChanged());
3501        assertTrue(result.hasProxyChanged());
3502
3503        verifyNetworkAddBroadcast(configuration);
3504        // Verify that the config store write was triggered with this new configuration.
3505        verifyNetworkInConfigStoreData(configuration);
3506        return result;
3507    }
3508
3509    /**
3510     * Add ephemeral network to WifiConfigManager and ensure that it was successful.
3511     */
3512    private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager(
3513            WifiConfiguration configuration) throws Exception {
3514        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
3515        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3516        assertTrue(result.isNewNetwork());
3517        assertTrue(result.hasIpChanged());
3518        assertTrue(result.hasProxyChanged());
3519
3520        verifyNetworkAddBroadcast(configuration);
3521        // Ensure that the write was not invoked for ephemeral network addition.
3522        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3523        return result;
3524    }
3525
3526    /**
3527     * Add Passpoint network to WifiConfigManager and ensure that it was successful.
3528     */
3529    private NetworkUpdateResult verifyAddPasspointNetworkToWifiConfigManager(
3530            WifiConfiguration configuration) throws Exception {
3531        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
3532        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3533        assertTrue(result.isNewNetwork());
3534        assertTrue(result.hasIpChanged());
3535        assertTrue(result.hasProxyChanged());
3536
3537        // Verify keys are not being installed.
3538        verify(mWifiKeyStore, never()).updateNetworkKeys(any(WifiConfiguration.class),
3539                any(WifiConfiguration.class));
3540        verifyNetworkAddBroadcast(configuration);
3541        // Ensure that the write was not invoked for Passpoint network addition.
3542        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3543        return result;
3544    }
3545
3546    /**
3547     * Updates the provided configuration to WifiConfigManager and modifies the provided
3548     * configuration with update uid, package name and time.
3549     * These fields are populated internally by WifiConfigManager and hence we need
3550     * to modify the configuration before we compare the added network with the retrieved network.
3551     */
3552    private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) {
3553        when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
3554        NetworkUpdateResult result =
3555                mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID);
3556        setUpdateDebugParams(configuration);
3557        return result;
3558    }
3559
3560    /**
3561     * Update network to WifiConfigManager config change and ensure that it was successful.
3562     */
3563    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager(
3564            WifiConfiguration configuration) {
3565        NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration);
3566        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3567        assertFalse(result.isNewNetwork());
3568
3569        verifyNetworkUpdateBroadcast(configuration);
3570        // Verify that the config store write was triggered with this new configuration.
3571        verifyNetworkInConfigStoreData(configuration);
3572        return result;
3573    }
3574
3575    /**
3576     * Update network to WifiConfigManager without IP config change and ensure that it was
3577     * successful.
3578     */
3579    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(
3580            WifiConfiguration configuration) {
3581        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
3582        assertFalse(result.hasIpChanged());
3583        assertFalse(result.hasProxyChanged());
3584        return result;
3585    }
3586
3587    /**
3588     * Update network to WifiConfigManager with IP config change and ensure that it was
3589     * successful.
3590     */
3591    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange(
3592            WifiConfiguration configuration) {
3593        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
3594        assertTrue(result.hasIpChanged());
3595        assertTrue(result.hasProxyChanged());
3596        return result;
3597    }
3598
3599    /**
3600     * Removes network from WifiConfigManager and ensure that it was successful.
3601     */
3602    private void verifyRemoveNetworkFromWifiConfigManager(
3603            WifiConfiguration configuration) {
3604        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
3605
3606        verifyNetworkRemoveBroadcast(configuration);
3607        // Verify if the config store write was triggered without this new configuration.
3608        verifyNetworkNotInConfigStoreData(configuration);
3609    }
3610
3611    /**
3612     * Removes ephemeral network from WifiConfigManager and ensure that it was successful.
3613     */
3614    private void verifyRemoveEphemeralNetworkFromWifiConfigManager(
3615            WifiConfiguration configuration) throws Exception {
3616        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
3617
3618        verifyNetworkRemoveBroadcast(configuration);
3619        // Ensure that the write was not invoked for ephemeral network remove.
3620        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3621    }
3622
3623    /**
3624     * Removes Passpoint network from WifiConfigManager and ensure that it was successful.
3625     */
3626    private void verifyRemovePasspointNetworkFromWifiConfigManager(
3627            WifiConfiguration configuration) throws Exception {
3628        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
3629
3630        // Verify keys are not being removed.
3631        verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class));
3632        verifyNetworkRemoveBroadcast(configuration);
3633        // Ensure that the write was not invoked for Passpoint network remove.
3634        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3635    }
3636
3637    /**
3638     * Verifies the provided network's public status and ensures that the network change broadcast
3639     * has been sent out.
3640     */
3641    private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) {
3642        assertEquals(status, configuration.status);
3643        verifyNetworkUpdateBroadcast(configuration);
3644    }
3645
3646    /**
3647     * Verifies the network's selection status update.
3648     *
3649     * For temporarily disabled reasons, the method ensures that the status has changed only if
3650     * disable reason counter has exceeded the threshold.
3651     *
3652     * For permanently disabled/enabled reasons, the method ensures that the public status has
3653     * changed and the network change broadcast has been sent out.
3654     */
3655    private void verifyUpdateNetworkSelectionStatus(
3656            int networkId, int reason, int temporaryDisableReasonCounter) {
3657        when(mClock.getElapsedSinceBootMillis())
3658                .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS);
3659
3660        // Fetch the current status of the network before we try to update the status.
3661        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
3662        NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus();
3663        int currentDisableReason = currentStatus.getNetworkSelectionDisableReason();
3664
3665        // First set the status to the provided reason.
3666        assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason));
3667
3668        // Now fetch the network configuration and verify the new status of the network.
3669        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
3670
3671        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
3672        int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason();
3673        long retrievedDisableTime = retrievedStatus.getDisableTime();
3674        int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason);
3675        int disableReasonThreshold =
3676                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason];
3677
3678        if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) {
3679            assertEquals(reason, retrievedDisableReason);
3680            assertTrue(retrievedStatus.isNetworkEnabled());
3681            assertEquals(
3682                    NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
3683                    retrievedDisableTime);
3684            verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
3685        } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) {
3686            // For temporarily disabled networks, we need to ensure that the current status remains
3687            // until the threshold is crossed.
3688            assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter);
3689            if (retrievedDisableReasonCounter < disableReasonThreshold) {
3690                assertEquals(currentDisableReason, retrievedDisableReason);
3691                assertEquals(
3692                        currentStatus.getNetworkSelectionStatus(),
3693                        retrievedStatus.getNetworkSelectionStatus());
3694            } else {
3695                assertEquals(reason, retrievedDisableReason);
3696                assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
3697                assertEquals(
3698                        TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime);
3699            }
3700        } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) {
3701            assertEquals(reason, retrievedDisableReason);
3702            assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
3703            assertEquals(
3704                    NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
3705                    retrievedDisableTime);
3706            verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
3707        }
3708    }
3709
3710    /**
3711     * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency
3712     * values.
3713     */
3714    private ScanDetail createScanDetailForNetwork(
3715            WifiConfiguration configuration, String bssid, int level, int frequency) {
3716        String caps;
3717        if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
3718            caps = "[WPA2-PSK-CCMP]";
3719        } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)
3720                || configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
3721            caps = "[WPA2-EAP-CCMP]";
3722        } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)
3723                && WifiConfigurationUtil.hasAnyValidWepKey(configuration.wepKeys)) {
3724            caps = "[WEP]";
3725        } else {
3726            caps = "[]";
3727        }
3728        WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid());
3729        // Fill in 0's in the fields we don't care about.
3730        return new ScanDetail(
3731                ssid, bssid, caps, level, frequency, mClock.getUptimeSinceBootMillis(),
3732                mClock.getWallClockMillis());
3733    }
3734
3735    /**
3736     * Creates a scan detail corresponding to the provided network and BSSID value.
3737     */
3738    private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) {
3739        return createScanDetailForNetwork(configuration, bssid, 0, 0);
3740    }
3741
3742    /**
3743     * Creates a scan detail corresponding to the provided network and fixed BSSID value.
3744     */
3745    private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) {
3746        return createScanDetailForNetwork(configuration, TEST_BSSID);
3747    }
3748
3749    /**
3750     * Adds the provided network and then creates a scan detail corresponding to the network. The
3751     * method then creates a ScanDetail corresponding to the network and ensures that the network
3752     * is properly matched using
3753     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} and also
3754     * verifies that the provided scan detail was cached,
3755     */
3756    private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
3757            WifiConfiguration network) {
3758        // First add the provided network.
3759        verifyAddNetworkToWifiConfigManager(network);
3760
3761        // Now create a dummy scan detail corresponding to the network.
3762        ScanDetail scanDetail = createScanDetailForNetwork(network);
3763        ScanResult scanResult = scanDetail.getScanResult();
3764
3765        WifiConfiguration retrievedNetwork =
3766                mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail);
3767        // Retrieve the network with password data for comparison.
3768        retrievedNetwork =
3769                mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId);
3770
3771        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3772                network, retrievedNetwork);
3773
3774        // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
3775        ScanDetailCache retrievedScanDetailCache =
3776                mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId);
3777        assertEquals(1, retrievedScanDetailCache.size());
3778        ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID);
3779
3780        ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
3781    }
3782
3783    /**
3784     * Adds a new network and verifies that the |HasEverConnected| flag is set to false.
3785     */
3786    private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) {
3787        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
3788        WifiConfiguration retrievedNetwork =
3789                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
3790        assertFalse("Adding a new network should not have hasEverConnected set to true.",
3791                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
3792    }
3793
3794    /**
3795     * Updates an existing network with some credential change and verifies that the
3796     * |HasEverConnected| flag is set to false.
3797     */
3798    private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(
3799            WifiConfiguration network) {
3800        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
3801        WifiConfiguration retrievedNetwork =
3802                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
3803        assertFalse("Updating network credentials config should clear hasEverConnected.",
3804                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
3805    }
3806
3807    /**
3808     * Updates an existing network after connection using
3809     * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the
3810     * |HasEverConnected| flag is set to true.
3811     */
3812    private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) {
3813        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId));
3814        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
3815        assertTrue("hasEverConnected expected to be true after connection.",
3816                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
3817    }
3818
3819    /**
3820     * Sets up a user profiles for WifiConfigManager testing.
3821     *
3822     * @param userId Id of the user.
3823     */
3824    private void setupUserProfiles(int userId) {
3825        final UserInfo userInfo =
3826                new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY);
3827        List<UserInfo> userProfiles = Arrays.asList(userInfo);
3828        when(mUserManager.getProfiles(userId)).thenReturn(userProfiles);
3829        when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true);
3830    }
3831
3832}
3833