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