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