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