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