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