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 
17 package com.android.server.wifi;
18 
19 import static org.junit.Assert.*;
20 import static org.mockito.Mockito.*;
21 
22 import android.annotation.Nullable;
23 import android.app.ActivityManager;
24 import android.app.test.MockAnswerUtil.AnswerWithArguments;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.pm.ApplicationInfo;
28 import android.content.pm.PackageManager;
29 import android.net.IpConfiguration;
30 import android.net.MacAddress;
31 import android.net.wifi.ScanResult;
32 import android.net.wifi.WifiConfiguration;
33 import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
34 import android.net.wifi.WifiEnterpriseConfig;
35 import android.net.wifi.WifiInfo;
36 import android.net.wifi.WifiManager;
37 import android.net.wifi.WifiScanner;
38 import android.os.Handler;
39 import android.os.Process;
40 import android.os.UserHandle;
41 import android.os.UserManager;
42 import android.os.test.TestLooper;
43 import android.telephony.SubscriptionInfo;
44 import android.telephony.SubscriptionManager;
45 import android.telephony.TelephonyManager;
46 import android.text.TextUtils;
47 import android.util.ArrayMap;
48 import android.util.Pair;
49 
50 import androidx.test.filters.SmallTest;
51 
52 import com.android.dx.mockito.inline.extended.ExtendedMockito;
53 import com.android.server.wifi.WifiScoreCard.PerNetwork;
54 import com.android.server.wifi.proto.nano.WifiMetricsProto.UserActionEvent;
55 import com.android.server.wifi.util.LruConnectionTracker;
56 import com.android.server.wifi.util.WifiPermissionsUtil;
57 import com.android.server.wifi.util.WifiPermissionsWrapper;
58 import com.android.wifi.resources.R;
59 
60 import org.junit.After;
61 import org.junit.Before;
62 import org.junit.Test;
63 import org.mockito.ArgumentCaptor;
64 import org.mockito.InOrder;
65 import org.mockito.Mock;
66 import org.mockito.MockitoAnnotations;
67 import org.mockito.MockitoSession;
68 import org.mockito.quality.Strictness;
69 
70 import java.io.FileDescriptor;
71 import java.io.PrintWriter;
72 import java.io.StringWriter;
73 import java.util.ArrayList;
74 import java.util.Arrays;
75 import java.util.Collections;
76 import java.util.HashMap;
77 import java.util.HashSet;
78 import java.util.List;
79 import java.util.Map;
80 import java.util.Random;
81 import java.util.Set;
82 
83 /**
84  * Unit tests for {@link com.android.server.wifi.WifiConfigManager}.
85  */
86 @SmallTest
87 public class WifiConfigManagerTest extends WifiBaseTest {
88 
89     private static final String TEST_SSID = "\"test_ssid\"";
90     private static final String TEST_BSSID = "0a:08:5c:67:89:00";
91     private static final long TEST_WALLCLOCK_CREATION_TIME_MILLIS = 9845637;
92     private static final long TEST_WALLCLOCK_UPDATE_TIME_MILLIS = 75455637;
93     private static final long TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS = 29457631;
94     private static final int TEST_CREATOR_UID = WifiConfigurationTestUtil.TEST_UID;
95     private static final int TEST_NO_PERM_UID = 7;
96     private static final int TEST_UPDATE_UID = 4;
97     private static final int TEST_SYSUI_UID = 56;
98     private static final int TEST_DEFAULT_USER = UserHandle.USER_SYSTEM;
99     private static final int TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN = 5;
100     private static final Integer[] TEST_FREQ_LIST = {2400, 2450, 5150, 5175, 5650};
101     private static final String TEST_CREATOR_NAME = "com.wificonfigmanager.creator";
102     private static final String TEST_UPDATE_NAME = "com.wificonfigmanager.update";
103     private static final String TEST_NO_PERM_NAME = "com.wificonfigmanager.noperm";
104     private static final String TEST_WIFI_NAME = "android.uid.system";
105     private static final String TEST_DEFAULT_GW_MAC_ADDRESS = "0f:67:ad:ef:09:34";
106     private static final String TEST_STATIC_PROXY_HOST_1 = "192.168.48.1";
107     private static final int    TEST_STATIC_PROXY_PORT_1 = 8000;
108     private static final String TEST_STATIC_PROXY_EXCLUSION_LIST_1 = "";
109     private static final String TEST_PAC_PROXY_LOCATION_1 = "http://bleh";
110     private static final String TEST_STATIC_PROXY_HOST_2 = "192.168.1.1";
111     private static final int    TEST_STATIC_PROXY_PORT_2 = 3000;
112     private static final String TEST_STATIC_PROXY_EXCLUSION_LIST_2 = "";
113     private static final String TEST_PAC_PROXY_LOCATION_2 = "http://blah";
114     private static final int TEST_RSSI = -50;
115     private static final int TEST_FREQUENCY_1 = 2412;
116     private static final int MAX_BLOCKED_BSSID_PER_NETWORK = 10;
117     private static final MacAddress TEST_RANDOMIZED_MAC =
118             MacAddress.fromString("d2:11:19:34:a5:20");
119     private static final int DATA_SUBID = 1;
120     private static final String SYSUI_PACKAGE_NAME = "com.android.systemui";
121 
122     @Mock private Context mContext;
123     @Mock private Clock mClock;
124     @Mock private UserManager mUserManager;
125     @Mock private SubscriptionManager mSubscriptionManager;
126     @Mock private TelephonyManager mTelephonyManager;
127     @Mock private TelephonyManager mDataTelephonyManager;
128     @Mock private WifiKeyStore mWifiKeyStore;
129     @Mock private WifiConfigStore mWifiConfigStore;
130     @Mock private PackageManager mPackageManager;
131     @Mock private WifiPermissionsUtil mWifiPermissionsUtil;
132     @Mock private WifiPermissionsWrapper mWifiPermissionsWrapper;
133     @Mock private WifiInjector mWifiInjector;
134     @Mock private WifiLastResortWatchdog mWifiLastResortWatchdog;
135     @Mock private NetworkListSharedStoreData mNetworkListSharedStoreData;
136     @Mock private NetworkListUserStoreData mNetworkListUserStoreData;
137     @Mock private RandomizedMacStoreData mRandomizedMacStoreData;
138     @Mock private WifiConfigManager.OnNetworkUpdateListener mWcmListener;
139     @Mock private FrameworkFacade mFrameworkFacade;
140     @Mock private DeviceConfigFacade mDeviceConfigFacade;
141     @Mock private MacAddressUtil mMacAddressUtil;
142     @Mock private BssidBlocklistMonitor mBssidBlocklistMonitor;
143     @Mock private WifiNetworkSuggestionsManager mWifiNetworkSuggestionsManager;
144     @Mock private WifiScoreCard mWifiScoreCard;
145     @Mock private PerNetwork mPerNetwork;
146     @Mock private WifiMetrics mWifiMetrics;
147     private LruConnectionTracker mLruConnectionTracker;
148 
149     private MockResources mResources;
150     private InOrder mContextConfigStoreMockOrder;
151     private InOrder mNetworkListStoreDataMockOrder;
152     private WifiConfigManager mWifiConfigManager;
153     private boolean mStoreReadTriggered = false;
154     private TestLooper mLooper = new TestLooper();
155     private MockitoSession mSession;
156     private WifiCarrierInfoManager mWifiCarrierInfoManager;
157 
158 
159     /**
160      * Setup the mocks and an instance of WifiConfigManager before each test.
161      */
162     @Before
setUp()163     public void setUp() throws Exception {
164         MockitoAnnotations.initMocks(this);
165 
166         // Set up the inorder for verifications. This is needed to verify that the broadcasts,
167         // store writes for network updates followed by network additions are in the expected order.
168         mContextConfigStoreMockOrder = inOrder(mContext, mWifiConfigStore);
169         mNetworkListStoreDataMockOrder =
170                 inOrder(mNetworkListSharedStoreData, mNetworkListUserStoreData);
171 
172         // Set up the package name stuff & permission override.
173         when(mContext.getPackageManager()).thenReturn(mPackageManager);
174         mResources = new MockResources();
175         mResources.setBoolean(
176                 R.bool.config_wifi_only_link_same_credential_configurations, true);
177         mResources.setInteger(
178                 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
179                 TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN);
180         mResources.setBoolean(R.bool.config_wifi_connected_mac_randomization_supported, true);
181         mResources.setInteger(R.integer.config_wifiMaxPnoSsidCount, 16);
182         when(mContext.getResources()).thenReturn(mResources);
183 
184         // Setup UserManager profiles for the default user.
185         setupUserProfiles(TEST_DEFAULT_USER);
186 
187         doAnswer(new AnswerWithArguments() {
188             public String answer(int uid) throws Exception {
189                 if (uid == TEST_CREATOR_UID) {
190                     return TEST_CREATOR_NAME;
191                 } else if (uid == TEST_UPDATE_UID) {
192                     return TEST_UPDATE_NAME;
193                 } else if (uid == TEST_SYSUI_UID) {
194                     return SYSUI_PACKAGE_NAME;
195                 } else if (uid == TEST_NO_PERM_UID) {
196                     return TEST_NO_PERM_NAME;
197                 } else if (uid == Process.WIFI_UID) {
198                     return TEST_WIFI_NAME;
199                 }
200                 fail("Unexpected UID: " + uid);
201                 return "";
202             }
203         }).when(mPackageManager).getNameForUid(anyInt());
204 
205         when(mContext.getSystemService(ActivityManager.class))
206                 .thenReturn(mock(ActivityManager.class));
207 
208         when(mWifiKeyStore
209                 .updateNetworkKeys(any(WifiConfiguration.class), any()))
210                 .thenReturn(true);
211 
212         setupStoreDataForRead(new ArrayList<>(), new ArrayList<>());
213 
214         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
215         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), any())).thenReturn(false);
216         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), any())).thenReturn(false);
217         when(mWifiInjector.getWifiNetworkSuggestionsManager())
218                 .thenReturn(mWifiNetworkSuggestionsManager);
219         when(mWifiInjector.getBssidBlocklistMonitor()).thenReturn(mBssidBlocklistMonitor);
220         when(mWifiInjector.getWifiLastResortWatchdog()).thenReturn(mWifiLastResortWatchdog);
221         when(mWifiInjector.getWifiLastResortWatchdog().shouldIgnoreSsidUpdate())
222                 .thenReturn(false);
223         when(mWifiInjector.getMacAddressUtil()).thenReturn(mMacAddressUtil);
224         when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics);
225         when(mMacAddressUtil.calculatePersistentMac(any(), any())).thenReturn(TEST_RANDOMIZED_MAC);
226         when(mWifiScoreCard.lookupNetwork(any())).thenReturn(mPerNetwork);
227 
228         mWifiCarrierInfoManager = new WifiCarrierInfoManager(mTelephonyManager,
229                 mSubscriptionManager, mWifiInjector, mock(FrameworkFacade.class),
230                 mock(WifiContext.class), mock(WifiConfigStore.class), mock(Handler.class),
231                 mWifiMetrics);
232         mLruConnectionTracker = new LruConnectionTracker(100, mContext);
233         createWifiConfigManager();
234         mWifiConfigManager.addOnNetworkUpdateListener(mWcmListener);
235         // static mocking
236         mSession = ExtendedMockito.mockitoSession()
237                 .mockStatic(WifiConfigStore.class, withSettings().lenient())
238                 .strictness(Strictness.LENIENT)
239                 .startMocking();
240         when(WifiConfigStore.createUserFiles(anyInt(), anyBoolean())).thenReturn(mock(List.class));
241         when(mTelephonyManager.createForSubscriptionId(anyInt())).thenReturn(mDataTelephonyManager);
242     }
243 
244     /**
245      * Called after each test
246      */
247     @After
cleanup()248     public void cleanup() {
249         validateMockitoUsage();
250         if (mSession != null) {
251             mSession.finishMocking();
252         }
253     }
254 
255     /**
256      * Verifies that network retrieval via
257      * {@link WifiConfigManager#getConfiguredNetworks()} and
258      * {@link WifiConfigManager#getConfiguredNetworksWithPasswords()} works even if we have not
259      * yet loaded data from store.
260      */
261     @Test
testGetConfiguredNetworksBeforeLoadFromStore()262     public void testGetConfiguredNetworksBeforeLoadFromStore() {
263         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
264         assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
265     }
266 
267     /**
268      * Verifies that network addition via
269      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} fails if we have not
270      * yet loaded data from store.
271      */
272     @Test
testAddNetworkIsRejectedBeforeLoadFromStore()273     public void testAddNetworkIsRejectedBeforeLoadFromStore() {
274         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
275         assertFalse(
276                 mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID).isSuccess());
277     }
278 
279     /**
280      * Verifies the {@link WifiConfigManager#saveToStore(boolean)} is rejected until the store has
281      * been read first using {@link WifiConfigManager#loadFromStore()}.
282      */
283     @Test
testSaveToStoreIsRejectedBeforeLoadFromStore()284     public void testSaveToStoreIsRejectedBeforeLoadFromStore() throws Exception {
285         assertFalse(mWifiConfigManager.saveToStore(true));
286         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
287 
288         assertTrue(mWifiConfigManager.loadFromStore());
289         mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
290 
291         assertTrue(mWifiConfigManager.saveToStore(true));
292         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
293     }
294 
295     /**
296      * Verify that a randomized MAC address is generated even if the KeyStore operation fails.
297      */
298     @Test
testRandomizedMacIsGeneratedEvenIfKeyStoreFails()299     public void testRandomizedMacIsGeneratedEvenIfKeyStoreFails() {
300         when(mMacAddressUtil.calculatePersistentMac(any(), any())).thenReturn(null);
301 
302         // Try adding a network.
303         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
304         List<WifiConfiguration> networks = new ArrayList<>();
305         networks.add(openNetwork);
306         verifyAddNetworkToWifiConfigManager(openNetwork);
307         List<WifiConfiguration> retrievedNetworks =
308                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
309 
310         // Verify that we have attempted to generate the MAC address twice (1 retry)
311         verify(mMacAddressUtil, times(2)).calculatePersistentMac(any(), any());
312         assertEquals(1, retrievedNetworks.size());
313 
314         // Verify that despite KeyStore returning null, we are still getting a valid MAC address.
315         assertNotEquals(WifiInfo.DEFAULT_MAC_ADDRESS,
316                 retrievedNetworks.get(0).getRandomizedMacAddress().toString());
317     }
318 
319     /**
320      * Verifies the addition of a single network using
321      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
322      */
323     @Test
testAddSingleOpenNetwork()324     public void testAddSingleOpenNetwork() {
325         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
326         List<WifiConfiguration> networks = new ArrayList<>();
327         networks.add(openNetwork);
328 
329         verifyAddNetworkToWifiConfigManager(openNetwork);
330 
331         List<WifiConfiguration> retrievedNetworks =
332                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
333         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
334                 networks, retrievedNetworks);
335         // Ensure that the newly added network is disabled.
336         assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
337     }
338 
339     /**
340      * Verifies the addition of a WAPI-PSK network using
341      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
342      */
343     @Test
testAddWapiPskNetwork()344     public void testAddWapiPskNetwork() {
345         WifiConfiguration wapiPskNetwork = WifiConfigurationTestUtil.createWapiPskNetwork();
346         List<WifiConfiguration> networks = new ArrayList<>();
347         networks.add(wapiPskNetwork);
348 
349         verifyAddNetworkToWifiConfigManager(wapiPskNetwork);
350 
351         List<WifiConfiguration> retrievedNetworks =
352                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
353         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
354                 networks, retrievedNetworks);
355         // Ensure that the newly added network is disabled.
356         assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
357     }
358 
359     /**
360      * Verifies the addition of a WAPI-PSK network with hex bytes using
361      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
362      */
363     @Test
testAddWapiPskHexNetwork()364     public void testAddWapiPskHexNetwork() {
365         WifiConfiguration wapiPskNetwork = WifiConfigurationTestUtil.createWapiPskNetwork();
366         wapiPskNetwork.preSharedKey =
367             "123456780abcdef0123456780abcdef0";
368         List<WifiConfiguration> networks = new ArrayList<>();
369         networks.add(wapiPskNetwork);
370 
371         verifyAddNetworkToWifiConfigManager(wapiPskNetwork);
372 
373         List<WifiConfiguration> retrievedNetworks =
374                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
375         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
376                 networks, retrievedNetworks);
377         // Ensure that the newly added network is disabled.
378         assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
379     }
380 
381     /**
382      * Verifies the addition of a WAPI-CERT network using
383      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
384      */
385     @Test
testAddWapiCertNetwork()386     public void testAddWapiCertNetwork() {
387         WifiConfiguration wapiCertNetwork = WifiConfigurationTestUtil.createWapiCertNetwork();
388         List<WifiConfiguration> networks = new ArrayList<>();
389         networks.add(wapiCertNetwork);
390 
391         verifyAddNetworkToWifiConfigManager(wapiCertNetwork);
392 
393         List<WifiConfiguration> retrievedNetworks =
394                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
395         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
396                 networks, retrievedNetworks);
397         // Ensure that the newly added network is disabled.
398         assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
399     }
400 
401     /**
402      * Verifies the addition of a single network when the corresponding ephemeral network exists.
403      */
404     @Test
testAddSingleOpenNetworkWhenCorrespondingEphemeralNetworkExists()405     public void testAddSingleOpenNetworkWhenCorrespondingEphemeralNetworkExists() throws Exception {
406         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
407         List<WifiConfiguration> networks = new ArrayList<>();
408         networks.add(openNetwork);
409         WifiConfiguration ephemeralNetwork = new WifiConfiguration(openNetwork);
410         ephemeralNetwork.ephemeral = true;
411 
412         verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
413 
414         NetworkUpdateResult result = addNetworkToWifiConfigManager(openNetwork);
415         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
416         assertTrue(result.isNewNetwork());
417 
418         verifyNetworkRemoveBroadcast();
419         verifyNetworkAddBroadcast();
420 
421         // Verify that the config store write was triggered with this new configuration.
422         verifyNetworkInConfigStoreData(openNetwork);
423 
424         List<WifiConfiguration> retrievedNetworks =
425                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
426         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
427                 networks, retrievedNetworks);
428 
429         // Ensure that the newly added network is disabled.
430         assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
431     }
432 
433     /**
434      * Verifies the addition of an ephemeral network when the corresponding ephemeral network
435      * exists.
436      */
437     @Test
testAddEphemeralNetworkWhenCorrespondingEphemeralNetworkExists()438     public void testAddEphemeralNetworkWhenCorrespondingEphemeralNetworkExists() throws Exception {
439         WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
440         ephemeralNetwork.ephemeral = true;
441         List<WifiConfiguration> networks = new ArrayList<>();
442         networks.add(ephemeralNetwork);
443 
444         WifiConfiguration ephemeralNetwork2 = new WifiConfiguration(ephemeralNetwork);
445         verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
446 
447         NetworkUpdateResult result = addNetworkToWifiConfigManager(ephemeralNetwork2);
448         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
449         verifyNetworkUpdateBroadcast();
450 
451         // Ensure that the write was not invoked for ephemeral network addition.
452         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
453 
454         List<WifiConfiguration> retrievedNetworks =
455                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
456         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
457                 networks, retrievedNetworks);
458     }
459 
460     /**
461      * Verifies when adding a new network with already saved MAC, the saved MAC gets set to the
462      * internal WifiConfiguration.
463      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
464      */
465     @Test
testAddingNetworkWithMatchingMacAddressOverridesField()466     public void testAddingNetworkWithMatchingMacAddressOverridesField() {
467         int prevMappingSize = mWifiConfigManager.getRandomizedMacAddressMappingSize();
468         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
469         Map<String, String> randomizedMacAddressMapping = new HashMap<>();
470         final String randMac = "12:23:34:45:56:67";
471         randomizedMacAddressMapping.put(openNetwork.getKey(), randMac);
472         assertNotEquals(randMac, openNetwork.getRandomizedMacAddress());
473         when(mRandomizedMacStoreData.getMacMapping()).thenReturn(randomizedMacAddressMapping);
474 
475         // reads XML data storage
476         //mWifiConfigManager.loadFromStore();
477         verifyAddNetworkToWifiConfigManager(openNetwork);
478 
479         List<WifiConfiguration> retrievedNetworks =
480                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
481         assertEquals(randMac, retrievedNetworks.get(0).getRandomizedMacAddress().toString());
482         // Verify that for networks that we already have randomizedMacAddressMapping saved
483         // we are still correctly writing into the WifiConfigStore.
484         assertEquals(prevMappingSize + 1, mWifiConfigManager.getRandomizedMacAddressMappingSize());
485     }
486 
487     /**
488      * Verifies that when a network is added, removed, and then added back again, its randomized
489      * MAC address doesn't change.
490      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
491      */
492     @Test
testRandomizedMacAddressIsPersistedOverForgetNetwork()493     public void testRandomizedMacAddressIsPersistedOverForgetNetwork() {
494         int prevMappingSize = mWifiConfigManager.getRandomizedMacAddressMappingSize();
495         // Create and add an open network
496         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
497         verifyAddNetworkToWifiConfigManager(openNetwork);
498         List<WifiConfiguration> retrievedNetworks =
499                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
500 
501         // Gets the randomized MAC address of the network added.
502         final String randMac = retrievedNetworks.get(0).getRandomizedMacAddress().toString();
503         // This MAC should be different from the default, uninitialized randomized MAC.
504         assertNotEquals(openNetwork.getRandomizedMacAddress().toString(), randMac);
505 
506         // Remove the added network
507         verifyRemoveNetworkFromWifiConfigManager(openNetwork);
508         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
509 
510         // Adds the network back again and verify randomized MAC address stays the same.
511         verifyAddNetworkToWifiConfigManager(openNetwork);
512         retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
513         assertEquals(randMac, retrievedNetworks.get(0).getRandomizedMacAddress().toString());
514         // Verify that we are no longer persisting the randomized MAC address with WifiConfigStore.
515         assertEquals(prevMappingSize, mWifiConfigManager.getRandomizedMacAddressMappingSize());
516     }
517 
518     /**
519      * Verifies that when a network is read from xml storage, it is assigned a randomized MAC
520      * address if it doesn't have one yet. Then try removing the network and then add it back
521      * again and verify the randomized MAC didn't change.
522      */
523     @Test
testRandomizedMacAddressIsGeneratedForConfigurationReadFromStore()524     public void testRandomizedMacAddressIsGeneratedForConfigurationReadFromStore()
525             throws Exception {
526         // Create and add an open network
527         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
528         final String defaultMac = openNetwork.getRandomizedMacAddress().toString();
529         List<WifiConfiguration> sharedConfigList = new ArrayList<>();
530         sharedConfigList.add(openNetwork);
531 
532         // Setup xml storage
533         setupStoreDataForRead(sharedConfigList, new ArrayList<>());
534         assertTrue(mWifiConfigManager.loadFromStore());
535         verify(mWifiConfigStore).read();
536 
537         List<WifiConfiguration> retrievedNetworks =
538                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
539         // Gets the randomized MAC address of the network added.
540         final String randMac = retrievedNetworks.get(0).getRandomizedMacAddress().toString();
541         // This MAC should be different from the default, uninitialized randomized MAC.
542         assertNotEquals(defaultMac, randMac);
543 
544         assertTrue(mWifiConfigManager.removeNetwork(
545                 openNetwork.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
546         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
547 
548         // Adds the network back again and verify randomized MAC address stays the same.
549         mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID);
550         retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
551         assertEquals(randMac, retrievedNetworks.get(0).getRandomizedMacAddress().toString());
552     }
553 
554     /**
555      * Verifies the modification of a single network using
556      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
557      */
558     @Test
testUpdateSingleOpenNetwork()559     public void testUpdateSingleOpenNetwork() {
560         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
561                 ArgumentCaptor.forClass(WifiConfiguration.class);
562         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
563         List<WifiConfiguration> networks = new ArrayList<>();
564         networks.add(openNetwork);
565 
566         verifyAddNetworkToWifiConfigManager(openNetwork);
567         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
568         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
569         reset(mWcmListener);
570 
571         // Now change BSSID for the network.
572         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
573         // Change the trusted bit.
574         openNetwork.trusted = false;
575         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
576 
577         // Now verify that the modification has been effective.
578         List<WifiConfiguration> retrievedNetworks =
579                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
580         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
581                 networks, retrievedNetworks);
582         verify(mWcmListener).onNetworkUpdated(
583                 wifiConfigCaptor.capture(), wifiConfigCaptor.capture());
584         WifiConfiguration newConfig = wifiConfigCaptor.getAllValues().get(1);
585         WifiConfiguration oldConfig = wifiConfigCaptor.getAllValues().get(0);
586         assertEquals(openNetwork.networkId, newConfig.networkId);
587         assertFalse(newConfig.trusted);
588         assertEquals(TEST_BSSID, newConfig.BSSID);
589         assertEquals(openNetwork.networkId, oldConfig.networkId);
590         assertTrue(oldConfig.trusted);
591         assertNull(oldConfig.BSSID);
592     }
593 
594     /**
595      * Verifies the modification of a single network will remove its bssid from
596      * the blocklist.
597      */
598     @Test
testUpdateSingleOpenNetworkInBlockList()599     public void testUpdateSingleOpenNetworkInBlockList() {
600         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
601                 ArgumentCaptor.forClass(WifiConfiguration.class);
602         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
603         List<WifiConfiguration> networks = new ArrayList<>();
604         networks.add(openNetwork);
605 
606         verifyAddNetworkToWifiConfigManager(openNetwork);
607         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
608         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
609         reset(mWcmListener);
610 
611         // mock the simplest bssid block list
612         Map<String, String> mBssidStatusMap = new ArrayMap<>();
613         doAnswer(new AnswerWithArguments() {
614             public void answer(String ssid) {
615                 mBssidStatusMap.entrySet().removeIf(e -> e.getValue().equals(ssid));
616             }
617         }).when(mBssidBlocklistMonitor).clearBssidBlocklistForSsid(
618                 anyString());
619         doAnswer(new AnswerWithArguments() {
620             public int answer(String ssid) {
621                 return (int) mBssidStatusMap.entrySet().stream()
622                         .filter(e -> e.getValue().equals(ssid)).count();
623             }
624         }).when(mBssidBlocklistMonitor).getNumBlockedBssidsForSsid(
625                 anyString());
626         // add bssid to the blocklist
627         mBssidStatusMap.put(TEST_BSSID, openNetwork.SSID);
628         mBssidStatusMap.put("aa:bb:cc:dd:ee:ff", openNetwork.SSID);
629 
630         // Now change BSSID for the network.
631         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
632         // Change the trusted bit.
633         openNetwork.trusted = false;
634         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
635 
636         // Now verify that the modification has been effective.
637         List<WifiConfiguration> retrievedNetworks =
638                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
639         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
640                 networks, retrievedNetworks);
641         verify(mWcmListener).onNetworkUpdated(
642                 wifiConfigCaptor.capture(), wifiConfigCaptor.capture());
643         WifiConfiguration newConfig = wifiConfigCaptor.getAllValues().get(1);
644         WifiConfiguration oldConfig = wifiConfigCaptor.getAllValues().get(0);
645         assertEquals(openNetwork.networkId, newConfig.networkId);
646         assertFalse(newConfig.trusted);
647         assertEquals(TEST_BSSID, newConfig.BSSID);
648         assertEquals(openNetwork.networkId, oldConfig.networkId);
649         assertTrue(oldConfig.trusted);
650         assertNull(oldConfig.BSSID);
651 
652         assertEquals(0, mBssidBlocklistMonitor.getNumBlockedBssidsForSsid(openNetwork.SSID));
653     }
654 
655     /**
656      * Verifies that the device owner could modify other other fields in the Wificonfiguration
657      * but not the macRandomizationSetting field.
658      */
659     @Test
testCannotUpdateMacRandomizationSettingWithoutPermission()660     public void testCannotUpdateMacRandomizationSettingWithoutPermission() {
661         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
662                 ArgumentCaptor.forClass(WifiConfiguration.class);
663         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
664         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false);
665         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), any())).thenReturn(true);
666         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
667         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_PERSISTENT;
668 
669         verifyAddNetworkToWifiConfigManager(openNetwork);
670         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
671         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
672         reset(mWcmListener);
673 
674         // Change BSSID for the network and verify success
675         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
676         NetworkUpdateResult networkUpdateResult = updateNetworkToWifiConfigManager(openNetwork);
677         assertNotEquals(WifiConfiguration.INVALID_NETWORK_ID, networkUpdateResult.getNetworkId());
678 
679         // Now change the macRandomizationSetting and verify failure
680         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_NONE;
681         networkUpdateResult = updateNetworkToWifiConfigManager(openNetwork);
682         assertEquals(WifiConfiguration.INVALID_NETWORK_ID, networkUpdateResult.getNetworkId());
683     }
684 
685     /**
686      * Verifies that mac randomization settings could be modified by a caller with NETWORK_SETTINGS
687      * permission.
688      */
689     @Test
testCanUpdateMacRandomizationSettingWithNetworkSettingPermission()690     public void testCanUpdateMacRandomizationSettingWithNetworkSettingPermission() {
691         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
692                 ArgumentCaptor.forClass(WifiConfiguration.class);
693         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false);
694         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
695         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_PERSISTENT;
696         List<WifiConfiguration> networks = new ArrayList<>();
697         networks.add(openNetwork);
698 
699         verifyAddNetworkToWifiConfigManager(openNetwork);
700         // Verify user action event is not logged when the network is added
701         verify(mWifiMetrics, never()).logUserActionEvent(anyInt(), anyBoolean(), anyBoolean());
702         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
703         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
704         reset(mWcmListener);
705 
706         // Now change the macRandomizationSetting and verify success
707         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_NONE;
708         NetworkUpdateResult networkUpdateResult = updateNetworkToWifiConfigManager(openNetwork);
709         assertNotEquals(WifiConfiguration.INVALID_NETWORK_ID, networkUpdateResult.getNetworkId());
710         verify(mWifiMetrics).logUserActionEvent(
711                 UserActionEvent.EVENT_CONFIGURE_MAC_RANDOMIZATION_OFF, openNetwork.networkId);
712 
713         List<WifiConfiguration> retrievedNetworks =
714                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
715         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
716                 networks, retrievedNetworks);
717     }
718 
719     /**
720      * Verifies that mac randomization settings could be modified by a caller with
721      * NETWORK_SETUP_WIZARD permission.
722      */
723     @Test
testCanUpdateMacRandomizationSettingWithSetupWizardPermission()724     public void testCanUpdateMacRandomizationSettingWithSetupWizardPermission() {
725         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
726                 ArgumentCaptor.forClass(WifiConfiguration.class);
727         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
728         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(true);
729         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), any())).thenReturn(true);
730         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
731         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_PERSISTENT;
732         List<WifiConfiguration> networks = new ArrayList<>();
733         networks.add(openNetwork);
734 
735         verifyAddNetworkToWifiConfigManager(openNetwork);
736         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
737         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
738         reset(mWcmListener);
739 
740         // Now change the macRandomizationSetting and verify success
741         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_NONE;
742         NetworkUpdateResult networkUpdateResult = updateNetworkToWifiConfigManager(openNetwork);
743         assertNotEquals(WifiConfiguration.INVALID_NETWORK_ID, networkUpdateResult.getNetworkId());
744 
745         List<WifiConfiguration> retrievedNetworks =
746                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
747         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
748                 networks, retrievedNetworks);
749     }
750 
751     /**
752      * Verify that the mac randomization setting could be modified by the creator of a passpoint
753      * network.
754      */
755     @Test
testCanUpdateMacRandomizationSettingWithPasspointCreatorUid()756     public void testCanUpdateMacRandomizationSettingWithPasspointCreatorUid() throws Exception {
757         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
758                 ArgumentCaptor.forClass(WifiConfiguration.class);
759         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
760         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false);
761         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), any())).thenReturn(false);
762         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
763         // Disable MAC randomization and verify this is added in successfully.
764         passpointNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_NONE;
765         List<WifiConfiguration> networks = new ArrayList<>();
766         networks.add(passpointNetwork);
767 
768         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
769         // Ensure that configured network list is not empty.
770         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
771 
772         // Ensure that this is not returned in the saved network list.
773         assertTrue(mWifiConfigManager.getSavedNetworks(Process.WIFI_UID).isEmpty());
774         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
775         assertEquals(passpointNetwork.networkId, wifiConfigCaptor.getValue().networkId);
776 
777         List<WifiConfiguration> retrievedNetworks =
778                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
779         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
780                 networks, retrievedNetworks);
781     }
782 
783 
784     /**
785      * Verifies the addition of a single ephemeral network using
786      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
787      * the {@link WifiConfigManager#getSavedNetworks(int)} does not return this network.
788      */
789     @Test
testAddSingleEphemeralNetwork()790     public void testAddSingleEphemeralNetwork() throws Exception {
791         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
792                 ArgumentCaptor.forClass(WifiConfiguration.class);
793         WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
794         ephemeralNetwork.ephemeral = true;
795         List<WifiConfiguration> networks = new ArrayList<>();
796         networks.add(ephemeralNetwork);
797 
798         verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
799 
800         List<WifiConfiguration> retrievedNetworks =
801                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
802         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
803                 networks, retrievedNetworks);
804 
805         // Ensure that this is not returned in the saved network list.
806         assertTrue(mWifiConfigManager.getSavedNetworks(Process.WIFI_UID).isEmpty());
807         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
808         assertEquals(ephemeralNetwork.networkId, wifiConfigCaptor.getValue().networkId);
809     }
810 
addSinglePasspointNetwork(boolean isHomeProviderNetwork)811     private void addSinglePasspointNetwork(boolean isHomeProviderNetwork) throws Exception {
812         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
813                 ArgumentCaptor.forClass(WifiConfiguration.class);
814         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
815         passpointNetwork.isHomeProviderNetwork = isHomeProviderNetwork;
816 
817         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
818         // Ensure that configured network list is not empty.
819         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
820 
821         // Ensure that this is not returned in the saved network list.
822         assertTrue(mWifiConfigManager.getSavedNetworks(Process.WIFI_UID).isEmpty());
823         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
824         assertEquals(passpointNetwork.networkId, wifiConfigCaptor.getValue().networkId);
825         assertEquals(passpointNetwork.isHomeProviderNetwork,
826                 wifiConfigCaptor.getValue().isHomeProviderNetwork);
827     }
828 
829     /**
830      * Verifies the addition of a single home Passpoint network using
831      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
832      * the {@link WifiConfigManager#getSavedNetworks(int)} ()} does not return this network.
833      */
834     @Test
testAddSingleHomePasspointNetwork()835     public void testAddSingleHomePasspointNetwork() throws Exception {
836         addSinglePasspointNetwork(true);
837     }
838 
839     /**
840      * Verifies the addition of a single roaming Passpoint network using
841      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
842      * the {@link WifiConfigManager#getSavedNetworks(int)} ()} does not return this network.
843      */
844     @Test
testAddSingleRoamingPasspointNetwork()845     public void testAddSingleRoamingPasspointNetwork() throws Exception {
846         addSinglePasspointNetwork(false);
847     }
848 
849     /**
850      * Verifies the addition of 2 networks (1 normal and 1 ephemeral) using
851      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that
852      * the ephemeral network configuration is not persisted in config store.
853      */
854     @Test
testAddMultipleNetworksAndEnsureEphemeralNetworkNotPersisted()855     public void testAddMultipleNetworksAndEnsureEphemeralNetworkNotPersisted() {
856         WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
857         ephemeralNetwork.ephemeral = true;
858         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
859 
860         assertTrue(addNetworkToWifiConfigManager(ephemeralNetwork).isSuccess());
861         assertTrue(addNetworkToWifiConfigManager(openNetwork).isSuccess());
862 
863         // The open network addition should trigger a store write.
864         Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData =
865                 captureWriteNetworksListStoreData();
866         List<WifiConfiguration> networkList = new ArrayList<>();
867         networkList.addAll(networkListStoreData.first);
868         networkList.addAll(networkListStoreData.second);
869         assertFalse(isNetworkInConfigStoreData(ephemeralNetwork, networkList));
870         assertTrue(isNetworkInConfigStoreData(openNetwork, networkList));
871     }
872 
873     /**
874      * Verifies the addition of a single suggestion network using
875      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int, String)} and verifies
876      * that the {@link WifiConfigManager#getSavedNetworks()} does not return this network.
877      */
878     @Test
testAddSingleSuggestionNetwork()879     public void testAddSingleSuggestionNetwork() throws Exception {
880         WifiConfiguration suggestionNetwork = WifiConfigurationTestUtil.createEapNetwork();
881         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
882                 ArgumentCaptor.forClass(WifiConfiguration.class);
883         suggestionNetwork.ephemeral = true;
884         suggestionNetwork.fromWifiNetworkSuggestion = true;
885         List<WifiConfiguration> networks = new ArrayList<>();
886         networks.add(suggestionNetwork);
887 
888         verifyAddSuggestionOrRequestNetworkToWifiConfigManager(suggestionNetwork);
889         verify(mWifiKeyStore, never()).updateNetworkKeys(any(), any());
890 
891         List<WifiConfiguration> retrievedNetworks =
892                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
893         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
894                 networks, retrievedNetworks);
895 
896         // Ensure that this is not returned in the saved network list.
897         assertTrue(mWifiConfigManager.getSavedNetworks(Process.WIFI_UID).isEmpty());
898         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
899         assertEquals(suggestionNetwork.networkId, wifiConfigCaptor.getValue().networkId);
900         assertTrue(mWifiConfigManager
901                 .removeNetwork(suggestionNetwork.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
902         verify(mWifiKeyStore, never()).removeKeys(any());
903     }
904 
905     /**
906      * Verifies the addition of a single specifier network using
907      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int, String)} and verifies
908      * that the {@link WifiConfigManager#getSavedNetworks()} does not return this network.
909      */
910     @Test
testAddSingleSpecifierNetwork()911     public void testAddSingleSpecifierNetwork() throws Exception {
912         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
913                 ArgumentCaptor.forClass(WifiConfiguration.class);
914         WifiConfiguration suggestionNetwork = WifiConfigurationTestUtil.createOpenNetwork();
915         suggestionNetwork.ephemeral = true;
916         suggestionNetwork.fromWifiNetworkSpecifier = true;
917         List<WifiConfiguration> networks = new ArrayList<>();
918         networks.add(suggestionNetwork);
919 
920         verifyAddSuggestionOrRequestNetworkToWifiConfigManager(suggestionNetwork);
921 
922         List<WifiConfiguration> retrievedNetworks =
923                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
924         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
925                 networks, retrievedNetworks);
926 
927         // Ensure that this is not returned in the saved network list.
928         assertTrue(mWifiConfigManager.getSavedNetworks(Process.WIFI_UID).isEmpty());
929         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
930         assertEquals(suggestionNetwork.networkId, wifiConfigCaptor.getValue().networkId);
931     }
932 
933     /**
934      * Verifies that the modification of a single open network using
935      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with a UID which
936      * has no permission to modify the network fails.
937      */
938     @Test
testUpdateSingleOpenNetworkFailedDueToPermissionDenied()939     public void testUpdateSingleOpenNetworkFailedDueToPermissionDenied() throws Exception {
940         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
941         List<WifiConfiguration> networks = new ArrayList<>();
942         networks.add(openNetwork);
943 
944         verifyAddNetworkToWifiConfigManager(openNetwork);
945 
946         // Now change BSSID of the network.
947         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
948 
949         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
950 
951         // Update the same configuration and ensure that the operation failed.
952         NetworkUpdateResult result = updateNetworkToWifiConfigManager(openNetwork);
953         assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
954     }
955 
956     /**
957      * Verifies that the modification of a single open network using
958      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with the creator UID
959      * should always succeed.
960      */
961     @Test
testUpdateSingleOpenNetworkSuccessWithCreatorUID()962     public void testUpdateSingleOpenNetworkSuccessWithCreatorUID() throws Exception {
963         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
964         List<WifiConfiguration> networks = new ArrayList<>();
965         networks.add(openNetwork);
966 
967         verifyAddNetworkToWifiConfigManager(openNetwork);
968 
969         // Now change BSSID of the network.
970         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
971 
972         // Update the same configuration using the creator UID.
973         NetworkUpdateResult result =
974                 mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID);
975         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
976 
977         // Now verify that the modification has been effective.
978         List<WifiConfiguration> retrievedNetworks =
979                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
980         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
981                 networks, retrievedNetworks);
982     }
983 
984     /**
985      * Verifies the addition of a single PSK network using
986      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
987      * {@link WifiConfigManager#getSavedNetworks()} masks the password.
988      */
989     @Test
testAddSinglePskNetwork()990     public void testAddSinglePskNetwork() {
991         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
992         List<WifiConfiguration> networks = new ArrayList<>();
993         networks.add(pskNetwork);
994 
995         verifyAddNetworkToWifiConfigManager(pskNetwork);
996 
997         List<WifiConfiguration> retrievedNetworks =
998                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
999         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1000                 networks, retrievedNetworks);
1001 
1002         List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks(
1003                 Process.WIFI_UID);
1004         assertEquals(retrievedSavedNetworks.size(), 1);
1005         assertEquals(retrievedSavedNetworks.get(0).getKey(), pskNetwork.getKey());
1006         assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0));
1007     }
1008 
1009     /**
1010      * Verifies the addition of a single WEP network using
1011      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
1012      * {@link WifiConfigManager#getSavedNetworks()} masks the password.
1013      */
1014     @Test
testAddSingleWepNetwork()1015     public void testAddSingleWepNetwork() {
1016         WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1017         List<WifiConfiguration> networks = new ArrayList<>();
1018         networks.add(wepNetwork);
1019 
1020         verifyAddNetworkToWifiConfigManager(wepNetwork);
1021 
1022         List<WifiConfiguration> retrievedNetworks =
1023                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
1024         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1025                 networks, retrievedNetworks);
1026 
1027         List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks(
1028                 Process.WIFI_UID);
1029         assertEquals(retrievedSavedNetworks.size(), 1);
1030         assertEquals(retrievedSavedNetworks.get(0).getKey(), wepNetwork.getKey());
1031         assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0));
1032     }
1033 
1034     /**
1035      * Verifies the modification of an IpConfiguration using
1036      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
1037      */
1038     @Test
testUpdateIpConfiguration()1039     public void testUpdateIpConfiguration() {
1040         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1041         List<WifiConfiguration> networks = new ArrayList<>();
1042         networks.add(openNetwork);
1043 
1044         verifyAddNetworkToWifiConfigManager(openNetwork);
1045 
1046         // Now change BSSID of the network.
1047         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
1048 
1049         // Update the same configuration and ensure that the IP configuration change flags
1050         // are not set.
1051         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
1052 
1053         // Configure mock DevicePolicyManager to give Profile Owner permission so that we can modify
1054         // proxy settings on a configuration
1055         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), any())).thenReturn(true);
1056 
1057         // Change the IpConfiguration now and ensure that the IP configuration flags are set now.
1058         assertAndSetNetworkIpConfiguration(
1059                 openNetwork,
1060                 WifiConfigurationTestUtil.createStaticIpConfigurationWithStaticProxy());
1061         verifyUpdateNetworkToWifiConfigManagerWithIpChange(openNetwork);
1062 
1063         // Now verify that all the modifications have been effective.
1064         List<WifiConfiguration> retrievedNetworks =
1065                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
1066         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1067                 networks, retrievedNetworks);
1068     }
1069 
1070     /**
1071      * Verifies the removal of a single network using
1072      * {@link WifiConfigManager#removeNetwork(int)}
1073      */
1074     @Test
testRemoveSingleOpenNetwork()1075     public void testRemoveSingleOpenNetwork() {
1076         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
1077                 ArgumentCaptor.forClass(WifiConfiguration.class);
1078         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1079 
1080         verifyAddNetworkToWifiConfigManager(openNetwork);
1081         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
1082         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1083         reset(mWcmListener);
1084 
1085         // Ensure that configured network list is not empty.
1086         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1087 
1088         verifyRemoveNetworkFromWifiConfigManager(openNetwork);
1089         // Ensure that configured network list is empty now.
1090         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1091         verify(mWcmListener).onNetworkRemoved(wifiConfigCaptor.capture());
1092         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1093     }
1094 
1095     /**
1096      * Verifies the removal of an ephemeral network using
1097      * {@link WifiConfigManager#removeNetwork(int)}
1098      */
1099     @Test
testRemoveSingleEphemeralNetwork()1100     public void testRemoveSingleEphemeralNetwork() throws Exception {
1101         WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1102         ephemeralNetwork.ephemeral = true;
1103         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
1104                 ArgumentCaptor.forClass(WifiConfiguration.class);
1105 
1106         verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
1107         // Ensure that configured network list is not empty.
1108         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1109         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
1110         assertEquals(ephemeralNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1111         verifyRemoveEphemeralNetworkFromWifiConfigManager(ephemeralNetwork);
1112         // Ensure that configured network list is empty now.
1113         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1114         verify(mWcmListener).onNetworkRemoved(wifiConfigCaptor.capture());
1115         assertEquals(ephemeralNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1116     }
1117 
1118     /**
1119      * Verifies the removal of a Passpoint network using
1120      * {@link WifiConfigManager#removeNetwork(int)}
1121      */
1122     @Test
testRemoveSinglePasspointNetwork()1123     public void testRemoveSinglePasspointNetwork() throws Exception {
1124         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
1125                 ArgumentCaptor.forClass(WifiConfiguration.class);
1126         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
1127 
1128         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
1129         // Ensure that configured network list is not empty.
1130         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1131         verify(mWcmListener).onNetworkAdded(wifiConfigCaptor.capture());
1132         assertEquals(passpointNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1133 
1134         verifyRemovePasspointNetworkFromWifiConfigManager(passpointNetwork);
1135         // Ensure that configured network list is empty now.
1136         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1137         verify(mWcmListener).onNetworkRemoved(wifiConfigCaptor.capture());
1138         assertEquals(passpointNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1139     }
1140 
1141     /**
1142      * Verify that a Passpoint network that's added by an app with {@link #TEST_CREATOR_UID} can
1143      * be removed by WiFi Service with {@link Process#WIFI_UID}.
1144      *
1145      * @throws Exception
1146      */
1147     @Test
testRemovePasspointNetworkAddedByOther()1148     public void testRemovePasspointNetworkAddedByOther() throws Exception {
1149         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
1150 
1151         // Passpoint network is added using TEST_CREATOR_UID.
1152         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
1153         // Ensure that configured network list is not empty.
1154         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1155 
1156         assertTrue(mWifiConfigManager.removeNetwork(
1157                 passpointNetwork.networkId, Process.WIFI_UID, null));
1158 
1159         // Verify keys are not being removed.
1160         verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class));
1161         verifyNetworkRemoveBroadcast();
1162         // Ensure that the write was not invoked for Passpoint network remove.
1163         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
1164 
1165     }
1166     /**
1167      * Verifies the addition & update of multiple networks using
1168      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and the
1169      * removal of networks using
1170      * {@link WifiConfigManager#removeNetwork(int)}
1171      */
1172     @Test
testAddUpdateRemoveMultipleNetworks()1173     public void testAddUpdateRemoveMultipleNetworks() {
1174         List<WifiConfiguration> networks = new ArrayList<>();
1175         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1176         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1177         WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1178         networks.add(openNetwork);
1179         networks.add(pskNetwork);
1180         networks.add(wepNetwork);
1181 
1182         verifyAddNetworkToWifiConfigManager(openNetwork);
1183         verifyAddNetworkToWifiConfigManager(pskNetwork);
1184         verifyAddNetworkToWifiConfigManager(wepNetwork);
1185 
1186         // Now verify that all the additions has been effective.
1187         List<WifiConfiguration> retrievedNetworks =
1188                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
1189         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1190                 networks, retrievedNetworks);
1191 
1192         // Modify all the 3 configurations and update it to WifiConfigManager.
1193         assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
1194         assertAndSetNetworkBSSID(pskNetwork, TEST_BSSID);
1195         assertAndSetNetworkIpConfiguration(
1196                 wepNetwork,
1197                 WifiConfigurationTestUtil.createStaticIpConfigurationWithPacProxy());
1198 
1199         // Configure mock DevicePolicyManager to give Profile Owner permission so that we can modify
1200         // proxy settings on a configuration
1201         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), any())).thenReturn(true);
1202 
1203         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
1204         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork);
1205         verifyUpdateNetworkToWifiConfigManagerWithIpChange(wepNetwork);
1206         // Now verify that all the modifications has been effective.
1207         retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
1208         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1209                 networks, retrievedNetworks);
1210 
1211         // Now remove all 3 networks.
1212         verifyRemoveNetworkFromWifiConfigManager(openNetwork);
1213         verifyRemoveNetworkFromWifiConfigManager(pskNetwork);
1214         verifyRemoveNetworkFromWifiConfigManager(wepNetwork);
1215 
1216         // Ensure that configured network list is empty now.
1217         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1218     }
1219 
1220     /**
1221      * Verifies the update of network status using
1222      * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)}.
1223      */
1224     @Test
testNetworkSelectionStatus()1225     public void testNetworkSelectionStatus() {
1226         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
1227                 ArgumentCaptor.forClass(WifiConfiguration.class);
1228         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1229 
1230         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1231 
1232         int networkId = result.getNetworkId();
1233         // First set it to enabled.
1234         verifyUpdateNetworkSelectionStatus(
1235                 networkId, NetworkSelectionStatus.DISABLED_NONE, 0);
1236 
1237         // Now set it to temporarily disabled. The threshold for association rejection is 5, so
1238         // disable it 5 times to actually mark it temporarily disabled.
1239         int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
1240         int assocRejectThreshold =
1241                 WifiConfigManager.getNetworkSelectionDisableThreshold(assocRejectReason);
1242         for (int i = 1; i <= assocRejectThreshold; i++) {
1243             verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i);
1244         }
1245         verify(mWcmListener).onNetworkTemporarilyDisabled(wifiConfigCaptor.capture(),
1246                 eq(NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION));
1247         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1248         // Now set it to permanently disabled.
1249         verifyUpdateNetworkSelectionStatus(
1250                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER, 0);
1251         verify(mWcmListener).onNetworkPermanentlyDisabled(
1252                 wifiConfigCaptor.capture(), eq(NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER));
1253         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1254         // Now set it back to enabled.
1255         verifyUpdateNetworkSelectionStatus(
1256                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_NONE, 0);
1257         verify(mWcmListener, times(2))
1258                 .onNetworkEnabled(wifiConfigCaptor.capture());
1259         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1260     }
1261 
1262     /**
1263      * Verifies the update of network status using
1264      * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)}.
1265      */
1266     @Test
testNetworkSelectionStatusTemporarilyDisabledDueToNoInternet()1267     public void testNetworkSelectionStatusTemporarilyDisabledDueToNoInternet() {
1268         ArgumentCaptor<WifiConfiguration> wifiConfigCaptor =
1269                 ArgumentCaptor.forClass(WifiConfiguration.class);
1270         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1271 
1272         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1273 
1274         int networkId = result.getNetworkId();
1275         // First set it to enabled.
1276         verifyUpdateNetworkSelectionStatus(
1277                 networkId, NetworkSelectionStatus.DISABLED_NONE, 0);
1278 
1279         // Now set it to temporarily disabled. The threshold for no internet is 1, so
1280         // disable it once to actually mark it temporarily disabled.
1281         verifyUpdateNetworkSelectionStatus(result.getNetworkId(),
1282                 NetworkSelectionStatus.DISABLED_NO_INTERNET_TEMPORARY, 1);
1283         verify(mWcmListener).onNetworkTemporarilyDisabled(
1284                 wifiConfigCaptor.capture(),
1285                 eq(NetworkSelectionStatus.DISABLED_NO_INTERNET_TEMPORARY));
1286         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1287         // Now set it back to enabled.
1288         verifyUpdateNetworkSelectionStatus(
1289                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_NONE, 0);
1290         verify(mWcmListener, times(2))
1291                 .onNetworkEnabled(wifiConfigCaptor.capture());
1292         assertEquals(openNetwork.networkId, wifiConfigCaptor.getValue().networkId);
1293     }
1294 
1295     /**
1296      * Verifies the update of network status using
1297      * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and ensures that
1298      * enabling a network clears out all the temporary disable counters.
1299      */
1300     @Test
testNetworkSelectionStatusEnableClearsDisableCounters()1301     public void testNetworkSelectionStatusEnableClearsDisableCounters() {
1302         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1303 
1304         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1305 
1306         // First set it to enabled.
1307         verifyUpdateNetworkSelectionStatus(
1308                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_NONE, 0);
1309 
1310         // Now set it to temporarily disabled 2 times for 2 different reasons.
1311         verifyUpdateNetworkSelectionStatus(
1312                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1);
1313         verifyUpdateNetworkSelectionStatus(
1314                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 2);
1315         verifyUpdateNetworkSelectionStatus(
1316                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1);
1317         verifyUpdateNetworkSelectionStatus(
1318                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 2);
1319 
1320         // Now set it back to enabled.
1321         verifyUpdateNetworkSelectionStatus(
1322                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_NONE, 0);
1323 
1324         // Ensure that the counters have all been reset now.
1325         verifyUpdateNetworkSelectionStatus(
1326                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1);
1327         verifyUpdateNetworkSelectionStatus(
1328                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1);
1329     }
1330 
verifyDisableNetwork(NetworkUpdateResult result, int reason)1331     private void verifyDisableNetwork(NetworkUpdateResult result, int reason) {
1332         // First set it to enabled.
1333         verifyUpdateNetworkSelectionStatus(
1334                 result.getNetworkId(), NetworkSelectionStatus.DISABLED_NONE, 0);
1335 
1336         int disableThreshold =
1337                 WifiConfigManager.getNetworkSelectionDisableThreshold(reason);
1338         for (int i = 1; i <= disableThreshold; i++) {
1339             verifyUpdateNetworkSelectionStatus(result.getNetworkId(), reason, i);
1340         }
1341     }
1342 
verifyNetworkIsEnabledAfter(int networkId, long timeout)1343     private void verifyNetworkIsEnabledAfter(int networkId, long timeout) {
1344         // try enabling this network 1 second earlier than the expected timeout. This
1345         // should fail and the status should remain temporarily disabled.
1346         when(mClock.getElapsedSinceBootMillis()).thenReturn(timeout - 1);
1347         assertFalse(mWifiConfigManager.tryEnableNetwork(networkId));
1348         NetworkSelectionStatus retrievedStatus =
1349                 mWifiConfigManager.getConfiguredNetwork(networkId).getNetworkSelectionStatus();
1350         assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
1351 
1352         // Now advance time by the timeout for association rejection and ensure that the
1353         // network is now enabled.
1354         when(mClock.getElapsedSinceBootMillis()).thenReturn(timeout);
1355         assertTrue(mWifiConfigManager.tryEnableNetwork(networkId));
1356         retrievedStatus = mWifiConfigManager.getConfiguredNetwork(networkId)
1357                 .getNetworkSelectionStatus();
1358         assertTrue(retrievedStatus.isNetworkEnabled());
1359     }
1360 
1361     /**
1362      * Verifies the enabling of temporarily disabled network using
1363      * {@link WifiConfigManager#tryEnableNetwork(int)}.
1364      */
1365     @Test
testTryEnableNetwork()1366     public void testTryEnableNetwork() {
1367         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1368         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1369 
1370         // Verify exponential backoff on the disable duration based on number of BSSIDs in the
1371         // BSSID blocklist
1372         long multiplier = 1;
1373         int disableReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
1374         long timeout = 0;
1375         for (int i = 1; i < MAX_BLOCKED_BSSID_PER_NETWORK + 1; i++) {
1376             verifyDisableNetwork(result, disableReason);
1377             int numBssidsInBlocklist = i;
1378             when(mBssidBlocklistMonitor.getNumBlockedBssidsForSsid(anyString()))
1379                     .thenReturn(numBssidsInBlocklist);
1380             timeout = WifiConfigManager.getNetworkSelectionDisableTimeoutMillis(disableReason)
1381                     * multiplier;
1382             multiplier *= 2;
1383             verifyNetworkIsEnabledAfter(result.getNetworkId(),
1384                     TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS + timeout);
1385         }
1386 
1387         // Verify one last time that the disable duration is capped at some maximum.
1388         verifyDisableNetwork(result, disableReason);
1389         when(mBssidBlocklistMonitor.getNumBlockedBssidsForSsid(anyString()))
1390                 .thenReturn(MAX_BLOCKED_BSSID_PER_NETWORK + 1);
1391         verifyNetworkIsEnabledAfter(result.getNetworkId(),
1392                 TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS + timeout);
1393     }
1394 
1395     /**
1396      * Verifies that when no BSSIDs for a network is inside the BSSID blocklist then we
1397      * re-enable a network.
1398      */
1399     @Test
testTryEnableNetworkNoBssidsInBlocklist()1400     public void testTryEnableNetworkNoBssidsInBlocklist() {
1401         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1402         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1403         int disableReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
1404 
1405         // Verify that with 0 BSSIDs in blocklist we enable the network immediately
1406         verifyDisableNetwork(result, disableReason);
1407         when(mBssidBlocklistMonitor.getNumBlockedBssidsForSsid(anyString())).thenReturn(0);
1408         when(mClock.getElapsedSinceBootMillis())
1409                 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS);
1410         assertTrue(mWifiConfigManager.tryEnableNetwork(result.getNetworkId()));
1411         NetworkSelectionStatus retrievedStatus =
1412                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
1413                         .getNetworkSelectionStatus();
1414         assertTrue(retrievedStatus.isNetworkEnabled());
1415     }
1416 
1417     /**
1418      * Verifies the enabling of network using
1419      * {@link WifiConfigManager#enableNetwork(int, boolean, int)} and
1420      * {@link WifiConfigManager#disableNetwork(int, int)}.
1421      */
1422     @Test
testEnableDisableNetwork()1423     public void testEnableDisableNetwork() throws Exception {
1424         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1425 
1426         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1427 
1428         assertTrue(mWifiConfigManager.enableNetwork(
1429                 result.getNetworkId(), false, TEST_CREATOR_UID, TEST_CREATOR_NAME));
1430         WifiConfiguration retrievedNetwork =
1431                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1432         NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
1433         assertTrue(retrievedStatus.isNetworkEnabled());
1434         verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
1435         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(eq(true));
1436 
1437         // Now set it disabled.
1438         assertTrue(mWifiConfigManager.disableNetwork(
1439                 result.getNetworkId(), TEST_CREATOR_UID, TEST_CREATOR_NAME));
1440         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1441         retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
1442         assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
1443         verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
1444         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(eq(true));
1445     }
1446 
1447     /**
1448      * Verifies the enabling of network using
1449      * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with a UID which
1450      * has no permission to modify the network fails..
1451      */
1452     @Test
testEnableNetworkFailedDueToPermissionDenied()1453     public void testEnableNetworkFailedDueToPermissionDenied() throws Exception {
1454         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
1455 
1456         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1457         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1458 
1459         assertEquals(WifiConfiguration.INVALID_NETWORK_ID,
1460                 mWifiConfigManager.getLastSelectedNetwork());
1461 
1462         // Now try to set it enable with |TEST_UPDATE_UID|, it should fail and the network
1463         // should remain disabled.
1464         assertFalse(mWifiConfigManager.enableNetwork(
1465                 result.getNetworkId(), true, TEST_UPDATE_UID, TEST_UPDATE_NAME));
1466         WifiConfiguration retrievedNetwork =
1467                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1468         NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
1469         assertFalse(retrievedStatus.isNetworkEnabled());
1470         assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetwork.status);
1471 
1472         // Set last selected network even if the app has no permission to enable it.
1473         assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
1474     }
1475 
1476     /**
1477      * Verifies the enabling of network using
1478      * {@link WifiConfigManager#disableNetwork(int, int)} with a UID which
1479      * has no permission to modify the network fails..
1480      */
1481     @Test
testDisableNetworkFailedDueToPermissionDenied()1482     public void testDisableNetworkFailedDueToPermissionDenied() throws Exception {
1483         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
1484 
1485         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1486         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1487         assertTrue(mWifiConfigManager.enableNetwork(
1488                 result.getNetworkId(), true, TEST_CREATOR_UID, TEST_CREATOR_NAME));
1489 
1490         assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
1491 
1492         // Now try to set it disabled with |TEST_UPDATE_UID|, it should fail and the network
1493         // should remain enabled.
1494         assertFalse(mWifiConfigManager.disableNetwork(
1495                 result.getNetworkId(), TEST_UPDATE_UID, TEST_CREATOR_NAME));
1496         WifiConfiguration retrievedNetwork =
1497                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1498         NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
1499         assertTrue(retrievedStatus.isNetworkEnabled());
1500         assertEquals(WifiConfiguration.Status.ENABLED, retrievedNetwork.status);
1501 
1502         // Clear the last selected network even if the app has no permission to disable it.
1503         assertEquals(WifiConfiguration.INVALID_NETWORK_ID,
1504                 mWifiConfigManager.getLastSelectedNetwork());
1505     }
1506 
1507     /**
1508      * Verifies the allowance/disallowance of autojoin to a network using
1509      * {@link WifiConfigManager#allowAutojoin(int, boolean)}
1510      */
1511     @Test
testAllowDisallowAutojoin()1512     public void testAllowDisallowAutojoin() throws Exception {
1513         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1514 
1515         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1516 
1517         assertTrue(mWifiConfigManager.allowAutojoin(
1518                 result.getNetworkId(), true));
1519         WifiConfiguration retrievedNetwork =
1520                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1521         assertTrue(retrievedNetwork.allowAutojoin);
1522         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(eq(true));
1523 
1524         // Now set it disallow auto-join.
1525         assertTrue(mWifiConfigManager.allowAutojoin(
1526                 result.getNetworkId(), false));
1527         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1528         assertFalse(retrievedNetwork.allowAutojoin);
1529         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(eq(true));
1530     }
1531 
1532     /**
1533      * Verifies the updation of network's connectUid using
1534      * {@link WifiConfigManager#updateLastConnectUid(int, int)}.
1535      */
1536     @Test
testUpdateLastConnectUid()1537     public void testUpdateLastConnectUid() throws Exception {
1538         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1539 
1540         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1541 
1542         assertTrue(
1543                 mWifiConfigManager.updateLastConnectUid(
1544                         result.getNetworkId(), TEST_CREATOR_UID));
1545         WifiConfiguration retrievedNetwork =
1546                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1547         assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid);
1548     }
1549 
1550     /**
1551      * Verifies that any configuration update attempt with an null config is gracefully
1552      * handled.
1553      * This invokes {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
1554      */
1555     @Test
testAddOrUpdateNetworkWithNullConfig()1556     public void testAddOrUpdateNetworkWithNullConfig() {
1557         NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(null, TEST_CREATOR_UID);
1558         assertFalse(result.isSuccess());
1559     }
1560 
1561     /**
1562      * Verifies that attempting to remove a network without any configs stored will return false.
1563      * This tests the case where we have not loaded any configs, potentially due to a pending store
1564      * read.
1565      * This invokes {@link WifiConfigManager#removeNetwork(int)}.
1566      */
1567     @Test
testRemoveNetworkWithEmptyConfigStore()1568     public void testRemoveNetworkWithEmptyConfigStore() {
1569         int networkId = new Random().nextInt();
1570         assertFalse(mWifiConfigManager.removeNetwork(
1571                 networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
1572     }
1573 
1574     /**
1575      * Verifies that any configuration removal attempt with an invalid networkID is gracefully
1576      * handled.
1577      * This invokes {@link WifiConfigManager#removeNetwork(int)}.
1578      */
1579     @Test
testRemoveNetworkWithInvalidNetworkId()1580     public void testRemoveNetworkWithInvalidNetworkId() {
1581         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1582 
1583         verifyAddNetworkToWifiConfigManager(openNetwork);
1584 
1585         // Change the networkID to an invalid one.
1586         openNetwork.networkId++;
1587         assertFalse(mWifiConfigManager.removeNetwork(
1588                 openNetwork.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
1589     }
1590 
1591     /**
1592      * Verifies that any configuration update attempt with an invalid networkID is gracefully
1593      * handled.
1594      * This invokes {@link WifiConfigManager#enableNetwork(int, boolean, int)},
1595      * {@link WifiConfigManager#disableNetwork(int, int)},
1596      * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and
1597      * {@link WifiConfigManager#updateLastConnectUid(int, int)}.
1598      */
1599     @Test
testChangeConfigurationWithInvalidNetworkId()1600     public void testChangeConfigurationWithInvalidNetworkId() {
1601         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1602 
1603         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1604 
1605         assertFalse(mWifiConfigManager.enableNetwork(
1606                 result.getNetworkId() + 1, false, TEST_CREATOR_UID, TEST_CREATOR_NAME));
1607         assertFalse(mWifiConfigManager.disableNetwork(
1608                 result.getNetworkId() + 1, TEST_CREATOR_UID, TEST_CREATOR_NAME));
1609         assertFalse(mWifiConfigManager.updateNetworkSelectionStatus(
1610                 result.getNetworkId() + 1, NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER));
1611         assertFalse(mWifiConfigManager.updateLastConnectUid(
1612                 result.getNetworkId() + 1, TEST_CREATOR_UID));
1613     }
1614 
1615     /**
1616      * Verifies multiple modification of a single network using
1617      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
1618      * This test is basically checking if the apps can reset some of the fields of the config after
1619      * addition. The fields being reset in this test are the |preSharedKey| and |wepKeys|.
1620      * 1. Create an open network initially.
1621      * 2. Modify the added network config to a WEP network config with all the 4 keys set.
1622      * 3. Modify the added network config to a WEP network config with only 1 key set.
1623      * 4. Modify the added network config to a PSK network config.
1624      */
1625     @Test
testMultipleUpdatesSingleNetwork()1626     public void testMultipleUpdatesSingleNetwork() {
1627         WifiConfiguration network = WifiConfigurationTestUtil.createOpenNetwork();
1628         verifyAddNetworkToWifiConfigManager(network);
1629 
1630         // Now add |wepKeys| to the network. We don't need to update the |allowedKeyManagement|
1631         // fields for open to WEP conversion.
1632         String[] wepKeys =
1633                 Arrays.copyOf(WifiConfigurationTestUtil.TEST_WEP_KEYS,
1634                         WifiConfigurationTestUtil.TEST_WEP_KEYS.length);
1635         int wepTxKeyIdx = WifiConfigurationTestUtil.TEST_WEP_TX_KEY_INDEX;
1636         assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
1637 
1638         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
1639         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1640                 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
1641 
1642         // Now empty out 3 of the |wepKeys[]| and ensure that those keys have been reset correctly.
1643         for (int i = 1; i < network.wepKeys.length; i++) {
1644             wepKeys[i] = "";
1645         }
1646         wepTxKeyIdx = 0;
1647         assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
1648 
1649         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
1650         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1651                 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
1652 
1653         // Now change the config to a PSK network config by resetting the remaining |wepKey[0]|
1654         // field and setting the |preSharedKey| and |allowedKeyManagement| fields.
1655         wepKeys[0] = "";
1656         wepTxKeyIdx = -1;
1657         assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
1658         network.allowedKeyManagement.clear();
1659         network.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
1660         assertAndSetNetworkPreSharedKey(network, WifiConfigurationTestUtil.TEST_PSK);
1661 
1662         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
1663         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1664                 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
1665     }
1666 
1667     /**
1668      * Verifies the modification of a WifiEnteriseConfig using
1669      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
1670      */
1671     @Test
testUpdateWifiEnterpriseConfig()1672     public void testUpdateWifiEnterpriseConfig() {
1673         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
1674         verifyAddNetworkToWifiConfigManager(network);
1675 
1676         // Set the |password| field in WifiEnterpriseConfig and modify the config to PEAP/GTC.
1677         network.enterpriseConfig =
1678                 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
1679         assertAndSetNetworkEnterprisePassword(network, "test");
1680 
1681         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
1682         network.enterpriseConfig.setCaPath(WifiConfigurationTestUtil.TEST_CA_CERT_PATH);
1683         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1684                 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
1685 
1686         // Reset the |password| field in WifiEnterpriseConfig and modify the config to TLS/None.
1687         network.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
1688         network.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);
1689         assertAndSetNetworkEnterprisePassword(network, "");
1690 
1691         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
1692         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1693                 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
1694     }
1695 
1696     /**
1697      * Verifies the modification of a single network using
1698      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} by passing in nulls
1699      * in all the publicly exposed fields.
1700      */
1701     @Test
testUpdateSingleNetworkWithNullValues()1702     public void testUpdateSingleNetworkWithNullValues() {
1703         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
1704         verifyAddNetworkToWifiConfigManager(network);
1705 
1706         // Save a copy of the original network for comparison.
1707         WifiConfiguration originalNetwork = new WifiConfiguration(network);
1708 
1709         // Now set all the public fields to null and try updating the network.
1710         network.allowedAuthAlgorithms.clear();
1711         network.allowedProtocols.clear();
1712         network.allowedKeyManagement.clear();
1713         network.allowedPairwiseCiphers.clear();
1714         network.allowedGroupCiphers.clear();
1715         network.enterpriseConfig = null;
1716 
1717         // Update the network.
1718         NetworkUpdateResult result = updateNetworkToWifiConfigManager(network);
1719         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
1720         assertFalse(result.isNewNetwork());
1721 
1722         // Verify no changes to the original network configuration.
1723         verifyNetworkUpdateBroadcast();
1724         verifyNetworkInConfigStoreData(originalNetwork);
1725         assertFalse(result.hasIpChanged());
1726         assertFalse(result.hasProxyChanged());
1727 
1728         // Copy over the updated debug params to the original network config before comparison.
1729         originalNetwork.lastUpdateUid = network.lastUpdateUid;
1730         originalNetwork.lastUpdateName = network.lastUpdateName;
1731 
1732         // Now verify that there was no change to the network configurations.
1733         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1734                 originalNetwork,
1735                 mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId));
1736     }
1737 
1738     /**
1739      * Verifies the addition of a single network using
1740      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} by passing in null
1741      * in IpConfiguraion fails.
1742      */
1743     @Test
testAddSingleNetworkWithNullIpConfigurationFails()1744     public void testAddSingleNetworkWithNullIpConfigurationFails() {
1745         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
1746         network.setIpConfiguration(null);
1747         NetworkUpdateResult result =
1748                 mWifiConfigManager.addOrUpdateNetwork(network, TEST_CREATOR_UID);
1749         assertFalse(result.isSuccess());
1750     }
1751 
1752     /**
1753      * Verifies that the modification of a single network using
1754      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} does not modify
1755      * existing configuration if there is a failure.
1756      */
1757     @Test
testUpdateSingleNetworkFailureDoesNotModifyOriginal()1758     public void testUpdateSingleNetworkFailureDoesNotModifyOriginal() {
1759         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
1760         network.enterpriseConfig =
1761                 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
1762         verifyAddNetworkToWifiConfigManager(network);
1763 
1764         // Save a copy of the original network for comparison.
1765         WifiConfiguration originalNetwork = new WifiConfiguration(network);
1766 
1767         // Now modify the network's EAP method.
1768         network.enterpriseConfig =
1769                 WifiConfigurationTestUtil.createTLSWifiEnterpriseConfigWithNonePhase2();
1770 
1771         // Fail this update because of cert installation failure.
1772         when(mWifiKeyStore
1773                 .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class)))
1774                 .thenReturn(false);
1775         NetworkUpdateResult result =
1776                 mWifiConfigManager.addOrUpdateNetwork(network, TEST_UPDATE_UID);
1777         assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
1778 
1779         // Now verify that there was no change to the network configurations.
1780         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1781                 originalNetwork,
1782                 mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId));
1783     }
1784 
1785     /**
1786      * Verifies the matching of networks with different encryption types with the
1787      * corresponding scan detail using
1788      * {@link WifiConfigManager#getConfiguredNetworkForScanDetailAndCache(ScanDetail)}.
1789      * The test also verifies that the provided scan detail was cached,
1790      */
1791     @Test
testMatchScanDetailToNetworksAndCache()1792     public void testMatchScanDetailToNetworksAndCache() {
1793         // Create networks of different types and ensure that they're all matched using
1794         // the corresponding ScanDetail correctly.
1795         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1796                 WifiConfigurationTestUtil.createOpenNetwork());
1797         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1798                 WifiConfigurationTestUtil.createWepNetwork());
1799         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1800                 WifiConfigurationTestUtil.createPskNetwork());
1801         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1802                 WifiConfigurationTestUtil.createEapNetwork());
1803         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1804                 WifiConfigurationTestUtil.createSaeNetwork());
1805         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1806                 WifiConfigurationTestUtil.createOweNetwork());
1807         verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
1808                 WifiConfigurationTestUtil.createEapSuiteBNetwork());
1809     }
1810 
1811     /**
1812      * Verifies that scan details with wrong SSID/authentication types are not matched using
1813      * {@link WifiConfigManager#getConfiguredNetworkForScanDetailAndCache(ScanDetail)}
1814      * to the added networks.
1815      */
1816     @Test
testNoMatchScanDetailToNetwork()1817     public void testNoMatchScanDetailToNetwork() {
1818         // First create networks of different types.
1819         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1820         WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1821         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1822         WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
1823         WifiConfiguration saeNetwork = WifiConfigurationTestUtil.createSaeNetwork();
1824         WifiConfiguration oweNetwork = WifiConfigurationTestUtil.createOweNetwork();
1825         WifiConfiguration eapSuiteBNetwork = WifiConfigurationTestUtil.createEapSuiteBNetwork();
1826 
1827         // Now add them to WifiConfigManager.
1828         verifyAddNetworkToWifiConfigManager(openNetwork);
1829         verifyAddNetworkToWifiConfigManager(wepNetwork);
1830         verifyAddNetworkToWifiConfigManager(pskNetwork);
1831         verifyAddNetworkToWifiConfigManager(eapNetwork);
1832         verifyAddNetworkToWifiConfigManager(saeNetwork);
1833         verifyAddNetworkToWifiConfigManager(oweNetwork);
1834         verifyAddNetworkToWifiConfigManager(eapSuiteBNetwork);
1835 
1836         // Now create dummy scan detail corresponding to the networks.
1837         ScanDetail openNetworkScanDetail = createScanDetailForNetwork(openNetwork);
1838         ScanDetail wepNetworkScanDetail = createScanDetailForNetwork(wepNetwork);
1839         ScanDetail pskNetworkScanDetail = createScanDetailForNetwork(pskNetwork);
1840         ScanDetail eapNetworkScanDetail = createScanDetailForNetwork(eapNetwork);
1841         ScanDetail saeNetworkScanDetail = createScanDetailForNetwork(saeNetwork);
1842         ScanDetail oweNetworkScanDetail = createScanDetailForNetwork(oweNetwork);
1843         ScanDetail eapSuiteBNetworkScanDetail = createScanDetailForNetwork(eapSuiteBNetwork);
1844 
1845         // Now mix and match parameters from different scan details.
1846         openNetworkScanDetail.getScanResult().SSID =
1847                 wepNetworkScanDetail.getScanResult().SSID;
1848         wepNetworkScanDetail.getScanResult().capabilities =
1849                 pskNetworkScanDetail.getScanResult().capabilities;
1850         pskNetworkScanDetail.getScanResult().capabilities =
1851                 eapNetworkScanDetail.getScanResult().capabilities;
1852         eapNetworkScanDetail.getScanResult().capabilities =
1853                 saeNetworkScanDetail.getScanResult().capabilities;
1854         saeNetworkScanDetail.getScanResult().capabilities =
1855                 oweNetworkScanDetail.getScanResult().capabilities;
1856         oweNetworkScanDetail.getScanResult().capabilities =
1857                 eapSuiteBNetworkScanDetail.getScanResult().capabilities;
1858         eapSuiteBNetworkScanDetail.getScanResult().capabilities =
1859                 openNetworkScanDetail.getScanResult().capabilities;
1860 
1861 
1862         // Try to lookup a saved network using the modified scan details. All of these should fail.
1863         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1864                 openNetworkScanDetail));
1865         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1866                 wepNetworkScanDetail));
1867         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1868                 pskNetworkScanDetail));
1869         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1870                 eapNetworkScanDetail));
1871         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1872                 saeNetworkScanDetail));
1873         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1874                 oweNetworkScanDetail));
1875         assertNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
1876                 eapSuiteBNetworkScanDetail));
1877 
1878         // All the cache's should be empty as well.
1879         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId));
1880         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(wepNetwork.networkId));
1881         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(pskNetwork.networkId));
1882         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(eapNetwork.networkId));
1883         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(saeNetwork.networkId));
1884         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(oweNetwork.networkId));
1885         assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(eapSuiteBNetwork.networkId));
1886     }
1887 
1888     /**
1889      * Verifies that ScanDetail added for a network is cached correctly with network ID
1890      */
1891     @Test
testUpdateScanDetailForNetwork()1892     public void testUpdateScanDetailForNetwork() {
1893         // First add the provided network.
1894         WifiConfiguration testNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1895         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(testNetwork);
1896 
1897         // Now create a dummy scan detail corresponding to the network.
1898         ScanDetail scanDetail = createScanDetailForNetwork(testNetwork);
1899         ScanResult scanResult = scanDetail.getScanResult();
1900 
1901         mWifiConfigManager.updateScanDetailForNetwork(result.getNetworkId(), scanDetail);
1902 
1903         // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
1904         ScanDetailCache retrievedScanDetailCache =
1905                 mWifiConfigManager.getScanDetailCacheForNetwork(result.getNetworkId());
1906         assertEquals(1, retrievedScanDetailCache.size());
1907         ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID);
1908 
1909         ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
1910     }
1911 
1912     /**
1913      * Verifies that ScanDetail added for a network is cached correctly without network ID
1914      */
1915     @Test
testUpdateScanDetailCacheFromScanDetail()1916     public void testUpdateScanDetailCacheFromScanDetail() {
1917         // First add the provided network.
1918         WifiConfiguration testNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1919         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(testNetwork);
1920 
1921         // Now create a dummy scan detail corresponding to the network.
1922         ScanDetail scanDetail = createScanDetailForNetwork(testNetwork);
1923         ScanResult scanResult = scanDetail.getScanResult();
1924 
1925         mWifiConfigManager.updateScanDetailCacheFromScanDetail(scanDetail);
1926 
1927         // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
1928         ScanDetailCache retrievedScanDetailCache =
1929                 mWifiConfigManager.getScanDetailCacheForNetwork(result.getNetworkId());
1930         assertEquals(1, retrievedScanDetailCache.size());
1931         ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID);
1932 
1933         ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
1934     }
1935 
1936     /**
1937      * Verifies that scan detail cache is trimmed down when the size of the cache for a network
1938      * exceeds {@link WifiConfigManager#SCAN_CACHE_ENTRIES_MAX_SIZE}.
1939      */
1940     @Test
testScanDetailCacheTrimForNetwork()1941     public void testScanDetailCacheTrimForNetwork() {
1942         // Add a single network.
1943         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1944         verifyAddNetworkToWifiConfigManager(openNetwork);
1945 
1946         ScanDetailCache scanDetailCache;
1947         String testBssidPrefix = "00:a5:b8:c9:45:";
1948 
1949         // Modify |BSSID| field in the scan result and add copies of scan detail
1950         // |SCAN_CACHE_ENTRIES_MAX_SIZE| times.
1951         int scanDetailNum = 1;
1952         for (; scanDetailNum <= WifiConfigManager.SCAN_CACHE_ENTRIES_MAX_SIZE; scanDetailNum++) {
1953             // Create dummy scan detail caches with different BSSID for the network.
1954             ScanDetail scanDetail =
1955                     createScanDetailForNetwork(
1956                             openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum));
1957             assertNotNull(
1958                     mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(scanDetail));
1959 
1960             // The size of scan detail cache should keep growing until it hits
1961             // |SCAN_CACHE_ENTRIES_MAX_SIZE|.
1962             scanDetailCache =
1963                     mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId);
1964             assertEquals(scanDetailNum, scanDetailCache.size());
1965         }
1966 
1967         // Now add the |SCAN_CACHE_ENTRIES_MAX_SIZE + 1| entry. This should trigger the trim.
1968         ScanDetail scanDetail =
1969                 createScanDetailForNetwork(
1970                         openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum));
1971         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(scanDetail));
1972 
1973         // Retrieve the scan detail cache and ensure that the size was trimmed down to
1974         // |SCAN_CACHE_ENTRIES_TRIM_SIZE + 1|. The "+1" is to account for the new entry that
1975         // was added after the trim.
1976         scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId);
1977         assertEquals(WifiConfigManager.SCAN_CACHE_ENTRIES_TRIM_SIZE + 1, scanDetailCache.size());
1978     }
1979 
1980     /**
1981      * Verifies that hasEverConnected is false for a newly added network.
1982      */
1983     @Test
testAddNetworkHasEverConnectedFalse()1984     public void testAddNetworkHasEverConnectedFalse() {
1985         verifyAddNetworkHasEverConnectedFalse(WifiConfigurationTestUtil.createOpenNetwork());
1986     }
1987 
1988     /**
1989      * Verifies that hasEverConnected is false for a newly added network even when new config has
1990      * mistakenly set HasEverConnected to true.
1991      */
1992     @Test
testAddNetworkOverridesHasEverConnectedWhenTrueInNewConfig()1993     public void testAddNetworkOverridesHasEverConnectedWhenTrueInNewConfig() {
1994         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1995         openNetwork.getNetworkSelectionStatus().setHasEverConnected(true);
1996         verifyAddNetworkHasEverConnectedFalse(openNetwork);
1997     }
1998 
1999     /**
2000      * Verify that the |HasEverConnected| is set when
2001      * {@link WifiConfigManager#updateNetworkAfterConnect(int)} is invoked.
2002      */
2003     @Test
testUpdateConfigAfterConnectHasEverConnectedTrue()2004     public void testUpdateConfigAfterConnectHasEverConnectedTrue() {
2005         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
2006         verifyAddNetworkHasEverConnectedFalse(openNetwork);
2007         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(openNetwork.networkId);
2008     }
2009 
2010     /**
2011      * Verifies that hasEverConnected is cleared when a network config |preSharedKey| is updated.
2012      */
2013     @Test
testUpdatePreSharedKeyClearsHasEverConnected()2014     public void testUpdatePreSharedKeyClearsHasEverConnected() {
2015         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2016         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2017         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2018 
2019         // Now update the same network with a different psk.
2020         String newPsk = "\"newpassword\"";
2021         assertFalse(pskNetwork.preSharedKey.equals(newPsk));
2022         pskNetwork.preSharedKey = newPsk;
2023         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2024     }
2025 
2026     /**
2027      * Verifies that hasEverConnected is cleared when a network config |wepKeys| is updated.
2028      */
2029     @Test
testUpdateWepKeysClearsHasEverConnected()2030     public void testUpdateWepKeysClearsHasEverConnected() {
2031         WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
2032         verifyAddNetworkHasEverConnectedFalse(wepNetwork);
2033         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId);
2034 
2035         // Now update the same network with a different wep.
2036         assertFalse(wepNetwork.wepKeys[0].equals("newpassword"));
2037         wepNetwork.wepKeys[0] = "newpassword";
2038         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork);
2039     }
2040 
2041     /**
2042      * Verifies that hasEverConnected is cleared when a network config |wepTxKeyIndex| is updated.
2043      */
2044     @Test
testUpdateWepTxKeyClearsHasEverConnected()2045     public void testUpdateWepTxKeyClearsHasEverConnected() {
2046         WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
2047         verifyAddNetworkHasEverConnectedFalse(wepNetwork);
2048         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId);
2049 
2050         // Now update the same network with a different wep.
2051         assertFalse(wepNetwork.wepTxKeyIndex == 3);
2052         wepNetwork.wepTxKeyIndex = 3;
2053         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork);
2054     }
2055 
2056     /**
2057      * Verifies that hasEverConnected is cleared when a network config |allowedKeyManagement| is
2058      * updated.
2059      */
2060     @Test
testUpdateAllowedKeyManagementClearsHasEverConnected()2061     public void testUpdateAllowedKeyManagementClearsHasEverConnected() {
2062         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2063         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2064         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2065 
2066         assertFalse(pskNetwork.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X));
2067         pskNetwork.allowedKeyManagement.clear();
2068         pskNetwork.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
2069         pskNetwork.requirePmf = true;
2070         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2071     }
2072 
2073     /**
2074      * Verifies that hasEverConnected is cleared when a network config |allowedProtocol| is
2075      * updated.
2076      */
2077     @Test
testUpdateProtocolsClearsHasEverConnected()2078     public void testUpdateProtocolsClearsHasEverConnected() {
2079         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2080         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2081         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2082 
2083         assertFalse(pskNetwork.allowedProtocols.get(WifiConfiguration.Protocol.OSEN));
2084         pskNetwork.allowedProtocols.set(WifiConfiguration.Protocol.OSEN);
2085         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2086     }
2087 
2088     /**
2089      * Verifies that hasEverConnected is cleared when a network config |allowedAuthAlgorithms| is
2090      * updated.
2091      */
2092     @Test
testUpdateAllowedAuthAlgorithmsClearsHasEverConnected()2093     public void testUpdateAllowedAuthAlgorithmsClearsHasEverConnected() {
2094         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2095         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2096         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2097 
2098         assertFalse(pskNetwork.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.LEAP));
2099         pskNetwork.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP);
2100         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2101     }
2102 
2103     /**
2104      * Verifies that hasEverConnected is cleared when a network config |allowedPairwiseCiphers| is
2105      * updated.
2106      */
2107     @Test
testUpdateAllowedPairwiseCiphersClearsHasEverConnected()2108     public void testUpdateAllowedPairwiseCiphersClearsHasEverConnected() {
2109         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2110         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2111         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2112 
2113         assertFalse(pskNetwork.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.NONE));
2114         pskNetwork.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
2115         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2116     }
2117 
2118     /**
2119      * Verifies that hasEverConnected is cleared when a network config |allowedGroup| is
2120      * updated.
2121      */
2122     @Test
testUpdateAllowedGroupCiphersClearsHasEverConnected()2123     public void testUpdateAllowedGroupCiphersClearsHasEverConnected() {
2124         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2125         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2126         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2127 
2128         assertTrue(pskNetwork.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP104));
2129         pskNetwork.allowedGroupCiphers.clear(WifiConfiguration.GroupCipher.WEP104);
2130         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2131     }
2132 
2133     /**
2134      * Verifies that hasEverConnected is cleared when a network config |hiddenSSID| is
2135      * updated.
2136      */
2137     @Test
testUpdateHiddenSSIDClearsHasEverConnected()2138     public void testUpdateHiddenSSIDClearsHasEverConnected() {
2139         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2140         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2141         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2142 
2143         assertFalse(pskNetwork.hiddenSSID);
2144         pskNetwork.hiddenSSID = true;
2145         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
2146     }
2147 
2148     /**
2149      * Verifies that hasEverConnected is cleared when a network config |requirePMF| is
2150      * updated.
2151      */
2152     @Test
testUpdateRequirePMFClearsHasEverConnected()2153     public void testUpdateRequirePMFClearsHasEverConnected() {
2154         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
2155         verifyAddNetworkHasEverConnectedFalse(pskNetwork);
2156         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
2157 
2158         assertFalse(pskNetwork.requirePmf);
2159         pskNetwork.requirePmf = true;
2160 
2161         NetworkUpdateResult result =
2162                 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork);
2163         WifiConfiguration retrievedNetwork =
2164                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
2165         assertFalse("Updating network credentials config must clear hasEverConnected.",
2166                 retrievedNetwork.getNetworkSelectionStatus().hasEverConnected());
2167         assertTrue(result.hasCredentialChanged());
2168     }
2169 
2170     /**
2171      * Verifies that hasEverConnected is cleared when a network config |enterpriseConfig| is
2172      * updated.
2173      */
2174     @Test
testUpdateEnterpriseConfigClearsHasEverConnected()2175     public void testUpdateEnterpriseConfigClearsHasEverConnected() {
2176         WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
2177         eapNetwork.enterpriseConfig =
2178                 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
2179         verifyAddNetworkHasEverConnectedFalse(eapNetwork);
2180         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(eapNetwork.networkId);
2181 
2182         assertFalse(eapNetwork.enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS);
2183         eapNetwork.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
2184         verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(eapNetwork);
2185     }
2186 
2187     /**
2188      * Verifies that if the app sends back the masked passwords in an update, we ignore it.
2189      */
2190     @Test
testUpdateIgnoresMaskedPasswords()2191     public void testUpdateIgnoresMaskedPasswords() {
2192         WifiConfiguration someRandomNetworkWithAllMaskedFields =
2193                 WifiConfigurationTestUtil.createPskNetwork();
2194         someRandomNetworkWithAllMaskedFields.wepKeys = WifiConfigurationTestUtil.TEST_WEP_KEYS;
2195         someRandomNetworkWithAllMaskedFields.preSharedKey = WifiConfigurationTestUtil.TEST_PSK;
2196         someRandomNetworkWithAllMaskedFields.enterpriseConfig.setPassword(
2197                 WifiConfigurationTestUtil.TEST_EAP_PASSWORD);
2198 
2199         NetworkUpdateResult result =
2200                 verifyAddNetworkToWifiConfigManager(someRandomNetworkWithAllMaskedFields);
2201 
2202         // All of these passwords must be masked in this retrieved network config.
2203         WifiConfiguration retrievedNetworkWithMaskedPassword =
2204                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
2205         assertPasswordsMaskedInWifiConfiguration(retrievedNetworkWithMaskedPassword);
2206         // Ensure that the passwords are present internally.
2207         WifiConfiguration retrievedNetworkWithPassword =
2208                 mWifiConfigManager.getConfiguredNetworkWithPassword(result.getNetworkId());
2209         assertEquals(someRandomNetworkWithAllMaskedFields.preSharedKey,
2210                 retrievedNetworkWithPassword.preSharedKey);
2211         assertEquals(someRandomNetworkWithAllMaskedFields.wepKeys,
2212                 retrievedNetworkWithPassword.wepKeys);
2213         assertEquals(someRandomNetworkWithAllMaskedFields.enterpriseConfig.getPassword(),
2214                 retrievedNetworkWithPassword.enterpriseConfig.getPassword());
2215 
2216         // Now update the same network config using the masked config.
2217         verifyUpdateNetworkToWifiConfigManager(retrievedNetworkWithMaskedPassword);
2218 
2219         // Retrieve the network config with password and ensure that they have not been overwritten
2220         // with *.
2221         retrievedNetworkWithPassword =
2222                 mWifiConfigManager.getConfiguredNetworkWithPassword(result.getNetworkId());
2223         assertEquals(someRandomNetworkWithAllMaskedFields.preSharedKey,
2224                 retrievedNetworkWithPassword.preSharedKey);
2225         assertEquals(someRandomNetworkWithAllMaskedFields.wepKeys,
2226                 retrievedNetworkWithPassword.wepKeys);
2227         assertEquals(someRandomNetworkWithAllMaskedFields.enterpriseConfig.getPassword(),
2228                 retrievedNetworkWithPassword.enterpriseConfig.getPassword());
2229     }
2230 
2231     /**
2232      * Verifies that randomized MAC address is masked out when we return
2233      * external configs except when explicitly asked for MAC address.
2234      */
2235     @Test
testGetConfiguredNetworksMasksRandomizedMac()2236     public void testGetConfiguredNetworksMasksRandomizedMac() {
2237         int targetUidConfigNonCreator = TEST_CREATOR_UID + 100;
2238 
2239         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
2240         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(config);
2241 
2242         // Verify that randomized MAC address is masked when obtaining saved networks from
2243         // invalid UID
2244         List<WifiConfiguration> configs = mWifiConfigManager.getSavedNetworks(Process.INVALID_UID);
2245         assertEquals(1, configs.size());
2246         assertRandomizedMacAddressMaskedInWifiConfiguration(configs.get(0));
2247 
2248         // Verify that randomized MAC address is unmasked when obtaining saved networks from
2249         // system UID
2250         configs = mWifiConfigManager.getSavedNetworks(Process.WIFI_UID);
2251         assertEquals(1, configs.size());
2252         String macAddress = configs.get(0).getRandomizedMacAddress().toString();
2253         assertNotEquals(WifiInfo.DEFAULT_MAC_ADDRESS, macAddress);
2254 
2255         // Verify that randomized MAC address is masked when obtaining saved networks from
2256         // (carrier app) non-creator of the config
2257         configs = mWifiConfigManager.getSavedNetworks(targetUidConfigNonCreator);
2258         assertEquals(1, configs.size());
2259         assertRandomizedMacAddressMaskedInWifiConfiguration(configs.get(0));
2260 
2261         // Verify that randomized MAC address is unmasked when obtaining saved networks from
2262         // (carrier app) creator of the config
2263         configs = mWifiConfigManager.getSavedNetworks(TEST_CREATOR_UID);
2264         assertEquals(1, configs.size());
2265         assertEquals(macAddress, configs.get(0).getRandomizedMacAddress().toString());
2266 
2267         // Verify that randomized MAC address is unmasked when getting list of privileged (with
2268         // password) configurations
2269         WifiConfiguration configWithRandomizedMac = mWifiConfigManager
2270                 .getConfiguredNetworkWithPassword(result.getNetworkId());
2271         assertEquals(macAddress, configs.get(0).getRandomizedMacAddress().toString());
2272 
2273         // Ensure that the MAC address is present when asked for config with MAC address.
2274         configWithRandomizedMac = mWifiConfigManager
2275                 .getConfiguredNetworkWithoutMasking(result.getNetworkId());
2276         assertEquals(macAddress, configs.get(0).getRandomizedMacAddress().toString());
2277     }
2278 
2279     /**
2280      * Verify that the aggressive randomization whitelist works for passpoints. (by checking FQDN)
2281      */
2282     @Test
testShouldUseAggressiveRandomizationPasspoint()2283     public void testShouldUseAggressiveRandomizationPasspoint() {
2284         WifiConfiguration c = WifiConfigurationTestUtil.createPasspointNetwork();
2285         // Adds SSID to the whitelist.
2286         Set<String> ssidList = new HashSet<>();
2287         ssidList.add(c.SSID);
2288         when(mDeviceConfigFacade.getAggressiveMacRandomizationSsidAllowlist())
2289                 .thenReturn(ssidList);
2290 
2291         // Verify that if for passpoint networks we don't check for the SSID to be in the whitelist
2292         assertFalse(mWifiConfigManager.shouldUseAggressiveRandomization(c));
2293 
2294         // instead we check for the FQDN
2295         ssidList.clear();
2296         ssidList.add(c.FQDN);
2297         assertTrue(mWifiConfigManager.shouldUseAggressiveRandomization(c));
2298     }
2299 
2300     /**
2301      * Verify that when DeviceConfigFacade#isEnhancedMacRandomizationEnabled returns true, any
2302      * networks that already use randomized MAC use enhanced MAC randomization instead.
2303      */
2304     @Test
testEnhanecedMacRandomizationIsEnabledGlobally()2305     public void testEnhanecedMacRandomizationIsEnabledGlobally() {
2306         when(mFrameworkFacade.getIntegerSetting(eq(mContext),
2307                 eq(WifiConfigManager.ENHANCED_MAC_RANDOMIZATION_FEATURE_FORCE_ENABLE_FLAG),
2308                 anyInt())).thenReturn(1);
2309         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
2310         assertTrue(mWifiConfigManager.shouldUseAggressiveRandomization(config));
2311 
2312         config.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_NONE;
2313         assertFalse(mWifiConfigManager.shouldUseAggressiveRandomization(config));
2314     }
2315 
2316     /**
2317      * Verifies that getRandomizedMacAndUpdateIfNeeded updates the randomized MAC address and
2318      * |randomizedMacExpirationTimeMs| correctly.
2319      *
2320      * Then verify that getRandomizedMacAndUpdateIfNeeded sets the randomized MAC back to the
2321      * persistent MAC.
2322      */
2323     @Test
testRandomizedMacUpdateAndRestore()2324     public void testRandomizedMacUpdateAndRestore() {
2325         setUpWifiConfigurationForAggressiveRandomization();
2326         // get the aggressive randomized MAC address.
2327         WifiConfiguration config = getFirstInternalWifiConfiguration();
2328         final MacAddress aggressiveMac = config.getRandomizedMacAddress();
2329         assertNotEquals(WifiInfo.DEFAULT_MAC_ADDRESS, aggressiveMac.toString());
2330         assertEquals(TEST_WALLCLOCK_CREATION_TIME_MILLIS
2331                 + WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS,
2332                 config.randomizedMacExpirationTimeMs);
2333 
2334         // verify the new randomized mac should be different from the original mac.
2335         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS
2336                 + WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS + 1);
2337         MacAddress aggressiveMac2 = mWifiConfigManager.getRandomizedMacAndUpdateIfNeeded(config);
2338 
2339         // verify internal WifiConfiguration has MacAddress updated correctly by comparing the
2340         // MAC address from internal WifiConfiguration with the value returned by API.
2341         config = getFirstInternalWifiConfiguration();
2342         assertEquals(aggressiveMac2, config.getRandomizedMacAddress());
2343         assertNotEquals(aggressiveMac, aggressiveMac2);
2344 
2345         // Now disable aggressive randomization and verify the randomized MAC is changed back to
2346         // the persistent MAC.
2347         Set<String> blacklist = new HashSet<>();
2348         blacklist.add(config.SSID);
2349         when(mDeviceConfigFacade.getAggressiveMacRandomizationSsidBlocklist())
2350                 .thenReturn(blacklist);
2351         MacAddress persistentMac = mWifiConfigManager.getRandomizedMacAndUpdateIfNeeded(config);
2352 
2353         // verify internal WifiConfiguration has MacAddress updated correctly by comparing the
2354         // MAC address from internal WifiConfiguration with the value returned by API.
2355         config = getFirstInternalWifiConfiguration();
2356         assertEquals(persistentMac, config.getRandomizedMacAddress());
2357         assertNotEquals(persistentMac, aggressiveMac);
2358         assertNotEquals(persistentMac, aggressiveMac2);
2359     }
2360 
2361     /**
2362      * Verifies that the updateRandomizedMacExpireTime method correctly updates the
2363      * |randomizedMacExpirationTimeMs| field of the given WifiConfiguration.
2364      */
2365     @Test
testUpdateRandomizedMacExpireTime()2366     public void testUpdateRandomizedMacExpireTime() {
2367         setUpWifiConfigurationForAggressiveRandomization();
2368         WifiConfiguration config = getFirstInternalWifiConfiguration();
2369         when(mClock.getWallClockMillis()).thenReturn(0L);
2370 
2371         // verify that |AGGRESSIVE_MAC_REFRESH_MS_MIN| is honored as the lower bound.
2372         long dhcpLeaseTimeInSeconds = (WifiConfigManager.AGGRESSIVE_MAC_REFRESH_MS_MIN / 1000) - 1;
2373         mWifiConfigManager.updateRandomizedMacExpireTime(config, dhcpLeaseTimeInSeconds);
2374         config = getFirstInternalWifiConfiguration();
2375         assertEquals(WifiConfigManager.AGGRESSIVE_MAC_REFRESH_MS_MIN,
2376                 config.randomizedMacExpirationTimeMs);
2377 
2378         // verify that |AGGRESSIVE_MAC_REFRESH_MS_MAX| is honored as the upper bound.
2379         dhcpLeaseTimeInSeconds = (WifiConfigManager.AGGRESSIVE_MAC_REFRESH_MS_MAX / 1000) + 1;
2380         mWifiConfigManager.updateRandomizedMacExpireTime(config, dhcpLeaseTimeInSeconds);
2381         config = getFirstInternalWifiConfiguration();
2382         assertEquals(WifiConfigManager.AGGRESSIVE_MAC_REFRESH_MS_MAX,
2383                 config.randomizedMacExpirationTimeMs);
2384 
2385         // finally verify setting a valid value between the upper and lower bounds.
2386         dhcpLeaseTimeInSeconds = (WifiConfigManager.AGGRESSIVE_MAC_REFRESH_MS_MIN / 1000) + 5;
2387         mWifiConfigManager.updateRandomizedMacExpireTime(config, dhcpLeaseTimeInSeconds);
2388         config = getFirstInternalWifiConfiguration();
2389         assertEquals(WifiConfigManager.AGGRESSIVE_MAC_REFRESH_MS_MIN + 5000,
2390                 config.randomizedMacExpirationTimeMs);
2391     }
2392 
2393     /**
2394      * Verifies that the expiration time of the currently used aggressive MAC is set to the
2395      * maximum of some predefined time and the remaining DHCP lease duration at disconnect.
2396      */
2397     @Test
testRandomizedMacExpirationTimeUpdatedAtDisconnect()2398     public void testRandomizedMacExpirationTimeUpdatedAtDisconnect() {
2399         setUpWifiConfigurationForAggressiveRandomization();
2400         WifiConfiguration config = getFirstInternalWifiConfiguration();
2401         when(mClock.getWallClockMillis()).thenReturn(0L);
2402 
2403         // First set the DHCP expiration time to be longer than the predefined time.
2404         long dhcpLeaseTimeInSeconds = (WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS
2405                 / 1000) + 1;
2406         mWifiConfigManager.updateRandomizedMacExpireTime(config, dhcpLeaseTimeInSeconds);
2407         config = getFirstInternalWifiConfiguration();
2408         long expirationTime = config.randomizedMacExpirationTimeMs;
2409         assertEquals(WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS + 1000,
2410                 expirationTime);
2411 
2412         // Verify that network disconnect does not update the expiration time since the remaining
2413         // lease duration is greater.
2414         mWifiConfigManager.updateNetworkAfterDisconnect(config.networkId);
2415         config = getFirstInternalWifiConfiguration();
2416         assertEquals(expirationTime, config.randomizedMacExpirationTimeMs);
2417 
2418         // Simulate time moving forward, then verify that a network disconnection updates the
2419         // MAC address expiration time correctly.
2420         when(mClock.getWallClockMillis()).thenReturn(5000L);
2421         mWifiConfigManager.updateNetworkAfterDisconnect(config.networkId);
2422         config = getFirstInternalWifiConfiguration();
2423         assertEquals(WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS + 5000,
2424                 config.randomizedMacExpirationTimeMs);
2425     }
2426 
2427     /**
2428      * Verifies that the randomized MAC address is not updated when insufficient time have past
2429      * since the previous update.
2430      */
2431     @Test
testRandomizedMacIsNotUpdatedDueToTimeConstraint()2432     public void testRandomizedMacIsNotUpdatedDueToTimeConstraint() {
2433         setUpWifiConfigurationForAggressiveRandomization();
2434         // get the persistent randomized MAC address.
2435         WifiConfiguration config = getFirstInternalWifiConfiguration();
2436         final MacAddress aggressiveMac = config.getRandomizedMacAddress();
2437         assertNotEquals(WifiInfo.DEFAULT_MAC_ADDRESS, aggressiveMac.toString());
2438         assertEquals(TEST_WALLCLOCK_CREATION_TIME_MILLIS
2439                 + WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS,
2440                 config.randomizedMacExpirationTimeMs);
2441 
2442         // verify that the randomized MAC is unchanged.
2443         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS
2444                 + WifiConfigManager.AGGRESSIVE_MAC_WAIT_AFTER_DISCONNECT_MS);
2445         MacAddress newMac = mWifiConfigManager.getRandomizedMacAndUpdateIfNeeded(config);
2446         assertEquals(aggressiveMac, newMac);
2447     }
2448 
2449     /**
2450      * Verifies that aggressive randomization SSID lists from DeviceConfig and overlay are being
2451      * combined together properly.
2452      */
2453     @Test
testPerDeviceAggressiveRandomizationSsids()2454     public void testPerDeviceAggressiveRandomizationSsids() {
2455         // This will add the SSID to allowlist using DeviceConfig.
2456         setUpWifiConfigurationForAggressiveRandomization();
2457         WifiConfiguration config = getFirstInternalWifiConfiguration();
2458         MacAddress aggressiveMac = config.getRandomizedMacAddress();
2459 
2460         // add to aggressive randomization blocklist using overlay.
2461         mResources.setStringArray(R.array.config_wifi_aggressive_randomization_ssid_blocklist,
2462                 new String[] {config.SSID});
2463         MacAddress persistentMac = mWifiConfigManager.getRandomizedMacAndUpdateIfNeeded(config);
2464         // verify that now the persistent randomized MAC is used.
2465         assertNotEquals(aggressiveMac, persistentMac);
2466     }
2467 
getFirstInternalWifiConfiguration()2468     private WifiConfiguration getFirstInternalWifiConfiguration() {
2469         List<WifiConfiguration> configs = mWifiConfigManager.getSavedNetworks(Process.WIFI_UID);
2470         assertEquals(1, configs.size());
2471         return configs.get(0);
2472     }
2473 
setUpWifiConfigurationForAggressiveRandomization()2474     private void setUpWifiConfigurationForAggressiveRandomization() {
2475         // sets up a WifiConfiguration for aggressive randomization.
2476         WifiConfiguration c = WifiConfigurationTestUtil.createOpenNetwork();
2477         // Adds the WifiConfiguration to aggressive randomization whitelist.
2478         Set<String> ssidList = new HashSet<>();
2479         ssidList.add(c.SSID);
2480         when(mDeviceConfigFacade.getAggressiveMacRandomizationSsidAllowlist())
2481                 .thenReturn(ssidList);
2482         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(c);
2483         mWifiConfigManager.updateNetworkAfterDisconnect(result.getNetworkId());
2484 
2485         // Verify the MAC address is valid, and is NOT calculated from the (SSID + security type)
2486         assertTrue(WifiConfiguration.isValidMacAddressForRandomization(
2487                 getFirstInternalWifiConfiguration().getRandomizedMacAddress()));
2488         verify(mMacAddressUtil, never()).calculatePersistentMac(any(), any());
2489     }
2490 
2491     /**
2492      * Verifies that macRandomizationSetting is not masked out when MAC randomization is supported.
2493      */
2494     @Test
testGetConfiguredNetworksNotMaskMacRandomizationSetting()2495     public void testGetConfiguredNetworksNotMaskMacRandomizationSetting() {
2496         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
2497         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(config);
2498 
2499         // Verify macRandomizationSetting is not masked out when feature is supported.
2500         List<WifiConfiguration> configs = mWifiConfigManager.getSavedNetworks(Process.WIFI_UID);
2501         assertEquals(1, configs.size());
2502         assertEquals(WifiConfiguration.RANDOMIZATION_PERSISTENT,
2503                 configs.get(0).macRandomizationSetting);
2504     }
2505 
2506     /**
2507      * Verifies that macRandomizationSetting is masked out to WifiConfiguration.RANDOMIZATION_NONE
2508      * when MAC randomization is not supported on the device.
2509      */
2510     @Test
testGetConfiguredNetworksMasksMacRandomizationSetting()2511     public void testGetConfiguredNetworksMasksMacRandomizationSetting() {
2512         mResources.setBoolean(R.bool.config_wifi_connected_mac_randomization_supported, false);
2513         createWifiConfigManager();
2514         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
2515         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(config);
2516 
2517         // Verify macRandomizationSetting is masked out when feature is unsupported.
2518         List<WifiConfiguration> configs = mWifiConfigManager.getSavedNetworks(Process.WIFI_UID);
2519         assertEquals(1, configs.size());
2520         assertEquals(WifiConfiguration.RANDOMIZATION_NONE, configs.get(0).macRandomizationSetting);
2521     }
2522 
2523     /**
2524      * Verifies that passwords are masked out when we return external configs except when
2525      * explicitly asked for them.
2526      */
2527     @Test
testGetConfiguredNetworksMasksPasswords()2528     public void testGetConfiguredNetworksMasksPasswords() {
2529         WifiConfiguration networkWithPasswords = WifiConfigurationTestUtil.createPskNetwork();
2530         networkWithPasswords.wepKeys = WifiConfigurationTestUtil.TEST_WEP_KEYS;
2531         networkWithPasswords.preSharedKey = WifiConfigurationTestUtil.TEST_PSK;
2532         networkWithPasswords.enterpriseConfig.setPassword(
2533                 WifiConfigurationTestUtil.TEST_EAP_PASSWORD);
2534 
2535         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(networkWithPasswords);
2536 
2537         // All of these passwords must be masked in this retrieved network config.
2538         WifiConfiguration retrievedNetworkWithMaskedPassword =
2539                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
2540         assertPasswordsMaskedInWifiConfiguration(retrievedNetworkWithMaskedPassword);
2541 
2542         // Ensure that the passwords are present when asked for configs with passwords.
2543         WifiConfiguration retrievedNetworkWithPassword =
2544                 mWifiConfigManager.getConfiguredNetworkWithPassword(result.getNetworkId());
2545         assertEquals(networkWithPasswords.preSharedKey, retrievedNetworkWithPassword.preSharedKey);
2546         assertEquals(networkWithPasswords.wepKeys, retrievedNetworkWithPassword.wepKeys);
2547         assertEquals(networkWithPasswords.enterpriseConfig.getPassword(),
2548                 retrievedNetworkWithPassword.enterpriseConfig.getPassword());
2549 
2550         retrievedNetworkWithPassword =
2551                 mWifiConfigManager.getConfiguredNetworkWithoutMasking(result.getNetworkId());
2552         assertEquals(networkWithPasswords.preSharedKey, retrievedNetworkWithPassword.preSharedKey);
2553         assertEquals(networkWithPasswords.wepKeys, retrievedNetworkWithPassword.wepKeys);
2554         assertEquals(networkWithPasswords.enterpriseConfig.getPassword(),
2555                 retrievedNetworkWithPassword.enterpriseConfig.getPassword());
2556     }
2557 
2558     /**
2559      * Verifies the linking of networks when they have the same default GW Mac address in
2560      * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
2561      */
2562     @Test
testNetworkLinkUsingGwMacAddress()2563     public void testNetworkLinkUsingGwMacAddress() {
2564         WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
2565         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2566         WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
2567         verifyAddNetworkToWifiConfigManager(network1);
2568         verifyAddNetworkToWifiConfigManager(network2);
2569         verifyAddNetworkToWifiConfigManager(network3);
2570 
2571         // Set the same default GW mac address for all of the networks.
2572         assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
2573                 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
2574         assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
2575                 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
2576         assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
2577                 network3.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
2578 
2579         // Now create dummy scan detail corresponding to the networks.
2580         ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1);
2581         ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2);
2582         ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3);
2583 
2584         // Now save all these scan details corresponding to each of this network and expect
2585         // all of these networks to be linked with each other.
2586         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2587                 networkScanDetail1));
2588         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2589                 networkScanDetail2));
2590         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2591                 networkScanDetail3));
2592 
2593         List<WifiConfiguration> retrievedNetworks =
2594                 mWifiConfigManager.getConfiguredNetworks();
2595         for (WifiConfiguration network : retrievedNetworks) {
2596             assertEquals(2, network.linkedConfigurations.size());
2597             for (WifiConfiguration otherNetwork : retrievedNetworks) {
2598                 if (otherNetwork == network) {
2599                     continue;
2600                 }
2601                 assertNotNull(network.linkedConfigurations.get(otherNetwork.getKey()));
2602             }
2603         }
2604     }
2605 
2606     /**
2607      * Verifies the linking of networks when they have scan results with same first 16 ASCII of
2608      * bssid in
2609      * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
2610      */
2611     @Test
testNetworkLinkUsingBSSIDMatch()2612     public void testNetworkLinkUsingBSSIDMatch() {
2613         WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
2614         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2615         WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
2616         verifyAddNetworkToWifiConfigManager(network1);
2617         verifyAddNetworkToWifiConfigManager(network2);
2618         verifyAddNetworkToWifiConfigManager(network3);
2619 
2620         // Create scan results with bssid which is different in only the last char.
2621         ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
2622         ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
2623         ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3, "af:89:56:34:56:69");
2624 
2625         // Now save all these scan details corresponding to each of this network and expect
2626         // all of these networks to be linked with each other.
2627         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2628                 networkScanDetail1));
2629         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2630                 networkScanDetail2));
2631         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2632                 networkScanDetail3));
2633 
2634         List<WifiConfiguration> retrievedNetworks =
2635                 mWifiConfigManager.getConfiguredNetworks();
2636         for (WifiConfiguration network : retrievedNetworks) {
2637             assertEquals(2, network.linkedConfigurations.size());
2638             for (WifiConfiguration otherNetwork : retrievedNetworks) {
2639                 if (otherNetwork == network) {
2640                     continue;
2641                 }
2642                 assertNotNull(network.linkedConfigurations.get(otherNetwork.getKey()));
2643             }
2644         }
2645     }
2646 
2647     /**
2648      * Verifies the linking of networks does not happen for non WPA networks when they have scan
2649      * results with same first 16 ASCII of bssid in
2650      * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
2651      */
2652     @Test
testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks()2653     public void testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks() {
2654         WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
2655         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2656         verifyAddNetworkToWifiConfigManager(network1);
2657         verifyAddNetworkToWifiConfigManager(network2);
2658 
2659         // Create scan results with bssid which is different in only the last char.
2660         ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
2661         ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
2662 
2663         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2664                 networkScanDetail1));
2665         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2666                 networkScanDetail2));
2667 
2668         List<WifiConfiguration> retrievedNetworks =
2669                 mWifiConfigManager.getConfiguredNetworks();
2670         for (WifiConfiguration network : retrievedNetworks) {
2671             assertNull(network.linkedConfigurations);
2672         }
2673     }
2674 
2675     /**
2676      * Verifies the linking of networks does not happen for networks with more than
2677      * {@link WifiConfigManager#LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES} scan
2678      * results with same first 16 ASCII of bssid in
2679      * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
2680      */
2681     @Test
testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize()2682     public void testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize() {
2683         WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
2684         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2685         verifyAddNetworkToWifiConfigManager(network1);
2686         verifyAddNetworkToWifiConfigManager(network2);
2687 
2688         // Create 7 scan results with bssid which is different in only the last char.
2689         String test_bssid_base = "af:89:56:34:56:6";
2690         int scan_result_num = 0;
2691         for (; scan_result_num < WifiConfigManager.LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES + 1;
2692              scan_result_num++) {
2693             ScanDetail networkScanDetail =
2694                     createScanDetailForNetwork(
2695                             network1, test_bssid_base + Integer.toString(scan_result_num));
2696             assertNotNull(
2697                     mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2698                             networkScanDetail));
2699         }
2700 
2701         // Now add 1 scan result to the other network with bssid which is different in only the
2702         // last char.
2703         ScanDetail networkScanDetail2 =
2704                 createScanDetailForNetwork(
2705                         network2, test_bssid_base + Integer.toString(scan_result_num++));
2706         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2707                 networkScanDetail2));
2708 
2709         List<WifiConfiguration> retrievedNetworks =
2710                 mWifiConfigManager.getConfiguredNetworks();
2711         for (WifiConfiguration network : retrievedNetworks) {
2712             assertNull(network.linkedConfigurations);
2713         }
2714     }
2715 
2716     /**
2717      * Verifies the linking of networks when they have scan results with same first 16 ASCII of
2718      * bssid in {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}
2719      * and then subsequently delinked when the networks have default gateway set which do not match.
2720      */
2721     @Test
testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress()2722     public void testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress() {
2723         WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
2724         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
2725         verifyAddNetworkToWifiConfigManager(network1);
2726         verifyAddNetworkToWifiConfigManager(network2);
2727 
2728         // Create scan results with bssid which is different in only the last char.
2729         ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
2730         ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
2731 
2732         // Now save all these scan details corresponding to each of this network and expect
2733         // all of these networks to be linked with each other.
2734         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2735                 networkScanDetail1));
2736         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2737                 networkScanDetail2));
2738 
2739         List<WifiConfiguration> retrievedNetworks =
2740                 mWifiConfigManager.getConfiguredNetworks();
2741         for (WifiConfiguration network : retrievedNetworks) {
2742             assertEquals(1, network.linkedConfigurations.size());
2743             for (WifiConfiguration otherNetwork : retrievedNetworks) {
2744                 if (otherNetwork == network) {
2745                     continue;
2746                 }
2747                 assertNotNull(network.linkedConfigurations.get(otherNetwork.getKey()));
2748             }
2749         }
2750 
2751         // Now Set different GW mac address for both the networks and ensure they're unlinked.
2752         assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
2753                 network1.networkId, "de:ad:fe:45:23:34"));
2754         assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
2755                 network2.networkId, "ad:de:fe:45:23:34"));
2756 
2757         // Add some dummy scan results again to re-evaluate the linking of networks.
2758         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2759                 createScanDetailForNetwork(network1, "af:89:56:34:45:67")));
2760         assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(
2761                 createScanDetailForNetwork(network1, "af:89:56:34:45:68")));
2762 
2763         retrievedNetworks = mWifiConfigManager.getConfiguredNetworks();
2764         for (WifiConfiguration network : retrievedNetworks) {
2765             assertNull(network.linkedConfigurations);
2766         }
2767     }
2768 
2769     /**
2770      * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2771      * and ensures that any shared private networks networkId is not changed.
2772      * Test scenario:
2773      * 1. Load the shared networks from shared store and user 1 store.
2774      * 2. Switch to user 2 and ensure that the shared network's Id is not changed.
2775      */
2776     @Test
testHandleUserSwitchDoesNotChangeSharedNetworksId()2777     public void testHandleUserSwitchDoesNotChangeSharedNetworksId() throws Exception {
2778         int user1 = TEST_DEFAULT_USER;
2779         int user2 = TEST_DEFAULT_USER + 1;
2780         setupUserProfiles(user2);
2781 
2782         int appId = 674;
2783         long currentTimeMs = 67823;
2784         when(mClock.getWallClockMillis()).thenReturn(currentTimeMs);
2785 
2786         // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
2787         final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
2788         user1Network.shared = false;
2789         user1Network.creatorUid = UserHandle.getUid(user1, appId);
2790         final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2791         user2Network.shared = false;
2792         user2Network.creatorUid = UserHandle.getUid(user2, appId);
2793         final WifiConfiguration sharedNetwork1 = WifiConfigurationTestUtil.createPskNetwork();
2794         final WifiConfiguration sharedNetwork2 = WifiConfigurationTestUtil.createPskNetwork();
2795 
2796         // Set up the store data that is loaded initially.
2797         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
2798             {
2799                 add(sharedNetwork1);
2800                 add(sharedNetwork2);
2801             }
2802         };
2803         List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() {
2804             {
2805                 add(user1Network);
2806             }
2807         };
2808         setupStoreDataForRead(sharedNetworks, user1Networks);
2809         assertTrue(mWifiConfigManager.loadFromStore());
2810         verify(mWifiConfigStore).read();
2811 
2812         // Fetch the network ID's assigned to the shared networks initially.
2813         int sharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID;
2814         int sharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID;
2815         List<WifiConfiguration> retrievedNetworks =
2816                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
2817         for (WifiConfiguration network : retrievedNetworks) {
2818             if (network.getKey().equals(sharedNetwork1.getKey())) {
2819                 sharedNetwork1Id = network.networkId;
2820             } else if (network.getKey().equals(sharedNetwork2.getKey())) {
2821                 sharedNetwork2Id = network.networkId;
2822             }
2823         }
2824         assertTrue(sharedNetwork1Id != WifiConfiguration.INVALID_NETWORK_ID);
2825         assertTrue(sharedNetwork2Id != WifiConfiguration.INVALID_NETWORK_ID);
2826         assertFalse(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(TEST_SSID));
2827 
2828         // Set up the user 2 store data that is loaded at user switch.
2829         List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() {
2830             {
2831                 add(user2Network);
2832             }
2833         };
2834         setupStoreDataForUserRead(user2Networks, new HashMap<>());
2835         // Now switch the user to user 2 and ensure that shared network's IDs have not changed.
2836         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
2837         mWifiConfigManager.handleUserSwitch(user2);
2838         verify(mWifiConfigStore).switchUserStoresAndRead(any(List.class));
2839 
2840         // Again fetch the network ID's assigned to the shared networks and ensure they have not
2841         // changed.
2842         int updatedSharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID;
2843         int updatedSharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID;
2844         retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
2845         for (WifiConfiguration network : retrievedNetworks) {
2846             if (network.getKey().equals(sharedNetwork1.getKey())) {
2847                 updatedSharedNetwork1Id = network.networkId;
2848             } else if (network.getKey().equals(sharedNetwork2.getKey())) {
2849                 updatedSharedNetwork2Id = network.networkId;
2850             }
2851         }
2852         assertEquals(sharedNetwork1Id, updatedSharedNetwork1Id);
2853         assertEquals(sharedNetwork2Id, updatedSharedNetwork2Id);
2854         assertFalse(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(TEST_SSID));
2855     }
2856 
2857     /**
2858      * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2859      * and ensures that any old user private networks are not visible anymore.
2860      * Test scenario:
2861      * 1. Load the shared networks from shared store and user 1 store.
2862      * 2. Switch to user 2 and ensure that the user 1's private network has been removed.
2863      */
2864     @Test
testHandleUserSwitchRemovesOldUserPrivateNetworks()2865     public void testHandleUserSwitchRemovesOldUserPrivateNetworks() throws Exception {
2866         int user1 = TEST_DEFAULT_USER;
2867         int user2 = TEST_DEFAULT_USER + 1;
2868         setupUserProfiles(user2);
2869 
2870         int appId = 674;
2871 
2872         // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
2873         final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
2874         user1Network.shared = false;
2875         user1Network.creatorUid = UserHandle.getUid(user1, appId);
2876         final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2877         user2Network.shared = false;
2878         user2Network.creatorUid = UserHandle.getUid(user2, appId);
2879         final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
2880 
2881         // Set up the store data that is loaded initially.
2882         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
2883             {
2884                 add(sharedNetwork);
2885             }
2886         };
2887         List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() {
2888             {
2889                 add(user1Network);
2890             }
2891         };
2892         setupStoreDataForRead(sharedNetworks, user1Networks);
2893         assertTrue(mWifiConfigManager.loadFromStore());
2894         verify(mWifiConfigStore).read();
2895 
2896         // Fetch the network ID assigned to the user 1 network initially.
2897         int user1NetworkId = WifiConfiguration.INVALID_NETWORK_ID;
2898         List<WifiConfiguration> retrievedNetworks =
2899                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
2900         for (WifiConfiguration network : retrievedNetworks) {
2901             if (network.getKey().equals(user1Network.getKey())) {
2902                 user1NetworkId = network.networkId;
2903             }
2904         }
2905 
2906         // Set up the user 2 store data that is loaded at user switch.
2907         List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() {
2908             {
2909                 add(user2Network);
2910             }
2911         };
2912         setupStoreDataForUserRead(user2Networks, new HashMap<>());
2913         // Now switch the user to user 2 and ensure that user 1's private network has been removed.
2914         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
2915         Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2);
2916         verify(mWifiConfigStore).switchUserStoresAndRead(any(List.class));
2917         assertTrue((removedNetworks.size() == 1) && (removedNetworks.contains(user1NetworkId)));
2918 
2919         // Set the expected networks to be |sharedNetwork| and |user2Network|.
2920         List<WifiConfiguration> expectedNetworks = new ArrayList<WifiConfiguration>() {
2921             {
2922                 add(sharedNetwork);
2923                 add(user2Network);
2924             }
2925         };
2926         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
2927                 expectedNetworks, mWifiConfigManager.getConfiguredNetworksWithPasswords());
2928 
2929         // Send another user switch  indication with the same user 2. This should be ignored and
2930         // hence should not remove any new networks.
2931         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
2932         removedNetworks = mWifiConfigManager.handleUserSwitch(user2);
2933         assertTrue(removedNetworks.isEmpty());
2934     }
2935 
2936     /**
2937      * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2938      * and ensures that user switch from a user with no private networks is handled.
2939      * Test scenario:
2940      * 1. Load the shared networks from shared store and emptu user 1 store.
2941      * 2. Switch to user 2 and ensure that no private networks were removed.
2942      */
2943     @Test
testHandleUserSwitchWithNoOldUserPrivateNetworks()2944     public void testHandleUserSwitchWithNoOldUserPrivateNetworks() throws Exception {
2945         int user1 = TEST_DEFAULT_USER;
2946         int user2 = TEST_DEFAULT_USER + 1;
2947         setupUserProfiles(user2);
2948 
2949         int appId = 674;
2950 
2951         // Create 2 networks. 1 for user2 and 1 shared.
2952         final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
2953         user2Network.shared = false;
2954         user2Network.creatorUid = UserHandle.getUid(user2, appId);
2955         final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
2956 
2957         // Set up the store data that is loaded initially.
2958         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
2959             {
2960                 add(sharedNetwork);
2961             }
2962         };
2963         setupStoreDataForRead(sharedNetworks, new ArrayList<>());
2964         assertTrue(mWifiConfigManager.loadFromStore());
2965         verify(mWifiConfigStore).read();
2966 
2967         // Set up the user 2 store data that is loaded at user switch.
2968         List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() {
2969             {
2970                 add(user2Network);
2971             }
2972         };
2973         setupStoreDataForUserRead(user2Networks, new HashMap<>());
2974         // Now switch the user to user 2 and ensure that no private network has been removed.
2975         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
2976         Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2);
2977         verify(mWifiConfigStore).switchUserStoresAndRead(any(List.class));
2978         assertTrue(removedNetworks.isEmpty());
2979     }
2980 
2981     /**
2982      * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
2983      * and ensures that any non current user private networks are moved to shared store file.
2984      * This test simulates the following test case:
2985      * 1. Loads the shared networks from shared store at bootup.
2986      * 2. Load the private networks from user store on user 1 unlock.
2987      * 3. Switch to user 2 and ensure that the user 2's private network has been moved to user 2's
2988      * private store file.
2989      */
2990     @Test
testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore()2991     public void testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore() throws Exception {
2992         int user1 = TEST_DEFAULT_USER;
2993         int user2 = TEST_DEFAULT_USER + 1;
2994         setupUserProfiles(user2);
2995 
2996         int appId = 674;
2997 
2998         // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
2999         final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
3000         user1Network.shared = false;
3001         user1Network.creatorUid = UserHandle.getUid(user1, appId);
3002         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(user1Network.creatorUid))
3003                 .thenReturn(false);
3004 
3005         final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
3006         user2Network.shared = false;
3007         user2Network.creatorUid = UserHandle.getUid(user2, appId);
3008         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(user2Network.creatorUid))
3009                 .thenReturn(false);
3010 
3011         final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
3012 
3013         // Set up the shared store data that is loaded at bootup. User 2's private network
3014         // is still in shared store because they have not yet logged-in after upgrade.
3015         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
3016             {
3017                 add(sharedNetwork);
3018                 add(user2Network);
3019             }
3020         };
3021         setupStoreDataForRead(sharedNetworks, new ArrayList<>());
3022         assertTrue(mWifiConfigManager.loadFromStore());
3023         verify(mWifiConfigStore).read();
3024 
3025         // Set up the user store data that is loaded at user unlock.
3026         List<WifiConfiguration> userNetworks = new ArrayList<WifiConfiguration>() {
3027             {
3028                 add(user1Network);
3029             }
3030         };
3031         setupStoreDataForUserRead(userNetworks, new HashMap<>());
3032         mWifiConfigManager.handleUserUnlock(user1);
3033         verify(mWifiConfigStore).switchUserStoresAndRead(any(List.class));
3034         // Capture the written data for the user 1 and ensure that it corresponds to what was
3035         // setup.
3036         Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList =
3037                 captureWriteNetworksListStoreData();
3038         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3039                 sharedNetworks, writtenNetworkList.first);
3040         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3041                 userNetworks, writtenNetworkList.second);
3042 
3043         // Now switch the user to user2 and ensure that user 2's private network has been moved to
3044         // the user store.
3045         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
3046         mWifiConfigManager.handleUserSwitch(user2);
3047         // Set the expected network list before comparing. user1Network should be in shared data.
3048         // Note: In the real world, user1Network will no longer be visible now because it should
3049         // already be in user1's private store file. But, we're purposefully exposing it
3050         // via |loadStoreData| to test if other user's private networks are pushed to shared store.
3051         List<WifiConfiguration> expectedSharedNetworks = new ArrayList<WifiConfiguration>() {
3052             {
3053                 add(sharedNetwork);
3054                 add(user1Network);
3055             }
3056         };
3057         List<WifiConfiguration> expectedUserNetworks = new ArrayList<WifiConfiguration>() {
3058             {
3059                 add(user2Network);
3060             }
3061         };
3062         // Capture the first written data triggered for saving the old user's network
3063         // configurations.
3064         writtenNetworkList = captureWriteNetworksListStoreData();
3065         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3066                 sharedNetworks, writtenNetworkList.first);
3067         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3068                 userNetworks, writtenNetworkList.second);
3069 
3070         // Now capture the next written data triggered after the switch and ensure that user 2's
3071         // network is now in user store data.
3072         writtenNetworkList = captureWriteNetworksListStoreData();
3073         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3074                 expectedSharedNetworks, writtenNetworkList.first);
3075         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3076                 expectedUserNetworks, writtenNetworkList.second);
3077     }
3078 
3079     /**
3080      * Verify that unlocking an user that owns a legacy Passpoint configuration (which is stored
3081      * temporarily in the share store) will migrate it to PasspointManager and removed from
3082      * the list of configured networks.
3083      *
3084      * @throws Exception
3085      */
3086     @Test
testHandleUserUnlockRemovePasspointConfigFromSharedConfig()3087     public void testHandleUserUnlockRemovePasspointConfigFromSharedConfig() throws Exception {
3088         int user1 = TEST_DEFAULT_USER;
3089         int appId = 674;
3090 
3091         final WifiConfiguration passpointConfig =
3092                 WifiConfigurationTestUtil.createPasspointNetwork();
3093         passpointConfig.creatorUid = UserHandle.getUid(user1, appId);
3094         passpointConfig.isLegacyPasspointConfig = true;
3095 
3096         // Set up the shared store data to contain one legacy Passpoint configuration.
3097         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
3098             {
3099                 add(passpointConfig);
3100             }
3101         };
3102         setupStoreDataForRead(sharedNetworks, new ArrayList<>());
3103         assertTrue(mWifiConfigManager.loadFromStore());
3104         verify(mWifiConfigStore).read();
3105         assertEquals(1, mWifiConfigManager.getConfiguredNetworks().size());
3106 
3107         // Unlock the owner of the legacy Passpoint configuration, verify it is removed from
3108         // the configured networks (migrated to PasspointManager).
3109         setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashMap<>());
3110         mWifiConfigManager.handleUserUnlock(user1);
3111         verify(mWifiConfigStore).switchUserStoresAndRead(any(List.class));
3112         Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList =
3113                 captureWriteNetworksListStoreData();
3114         assertTrue(writtenNetworkList.first.isEmpty());
3115         assertTrue(writtenNetworkList.second.isEmpty());
3116         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
3117     }
3118 
3119     /**
3120      * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
3121      * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is
3122      * read immediately if the user is unlocked during the switch.
3123      */
3124     @Test
testHandleUserSwitchWhenUnlocked()3125     public void testHandleUserSwitchWhenUnlocked() throws Exception {
3126         int user1 = TEST_DEFAULT_USER;
3127         int user2 = TEST_DEFAULT_USER + 1;
3128         setupUserProfiles(user2);
3129 
3130         // Set up the internal data first.
3131         assertTrue(mWifiConfigManager.loadFromStore());
3132 
3133         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3134         // user2 is unlocked and switched to foreground.
3135         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
3136         mWifiConfigManager.handleUserSwitch(user2);
3137         // Ensure that the read was invoked.
3138         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3139                 .switchUserStoresAndRead(any(List.class));
3140     }
3141 
3142     /**
3143      * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
3144      * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not
3145      * read until the user is unlocked.
3146      */
3147     @Test
testHandleUserSwitchWhenLocked()3148     public void testHandleUserSwitchWhenLocked() throws Exception {
3149         int user1 = TEST_DEFAULT_USER;
3150         int user2 = TEST_DEFAULT_USER + 1;
3151         setupUserProfiles(user2);
3152 
3153         // Set up the internal data first.
3154         assertTrue(mWifiConfigManager.loadFromStore());
3155 
3156         // user2 is locked and switched to foreground.
3157         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(false);
3158         mWifiConfigManager.handleUserSwitch(user2);
3159 
3160         // Ensure that the read was not invoked.
3161         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3162                 .switchUserStoresAndRead(any(List.class));
3163 
3164         // Now try unlocking some other user (user1), this should be ignored.
3165         mWifiConfigManager.handleUserUnlock(user1);
3166         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3167                 .switchUserStoresAndRead(any(List.class));
3168 
3169         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3170         // Unlock the user2 and ensure that we read the data now.
3171         mWifiConfigManager.handleUserUnlock(user2);
3172         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3173                 .switchUserStoresAndRead(any(List.class));
3174     }
3175 
3176     /**
3177      * Verifies that the user stop handling using {@link WifiConfigManager#handleUserStop(int)}
3178      * and ensures that the store is written only when the foreground user is stopped.
3179      */
3180     @Test
testHandleUserStop()3181     public void testHandleUserStop() throws Exception {
3182         int user1 = TEST_DEFAULT_USER;
3183         int user2 = TEST_DEFAULT_USER + 1;
3184         setupUserProfiles(user2);
3185 
3186         // Set up the internal data first.
3187         assertTrue(mWifiConfigManager.loadFromStore());
3188 
3189         // Try stopping background user2 first, this should not do anything.
3190         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(false);
3191         mWifiConfigManager.handleUserStop(user2);
3192         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3193                 .switchUserStoresAndRead(any(List.class));
3194 
3195         // Now try stopping the foreground user1, this should trigger a write to store.
3196         mWifiConfigManager.handleUserStop(user1);
3197         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3198                 .switchUserStoresAndRead(any(List.class));
3199         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
3200     }
3201 
3202     /**
3203      * Verifies that the user stop handling using {@link WifiConfigManager#handleUserStop(int)}
3204      * and ensures that the shared data is not lost when the foreground user is stopped.
3205      */
3206     @Test
testHandleUserStopDoesNotClearSharedData()3207     public void testHandleUserStopDoesNotClearSharedData() throws Exception {
3208         int user1 = TEST_DEFAULT_USER;
3209 
3210         //
3211         // Setup the database for the user before initiating stop.
3212         //
3213         int appId = 674;
3214         // Create 2 networks. 1 for user1, and 1 shared.
3215         final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
3216         user1Network.shared = false;
3217         user1Network.creatorUid = UserHandle.getUid(user1, appId);
3218         final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
3219 
3220         // Set up the store data that is loaded initially.
3221         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
3222             {
3223                 add(sharedNetwork);
3224             }
3225         };
3226         List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() {
3227             {
3228                 add(user1Network);
3229             }
3230         };
3231         setupStoreDataForRead(sharedNetworks, user1Networks);
3232         assertTrue(mWifiConfigManager.loadFromStore());
3233         verify(mWifiConfigStore).read();
3234 
3235         // Ensure that we have 2 networks in the database before the stop.
3236         assertEquals(2, mWifiConfigManager.getConfiguredNetworks().size());
3237 
3238         mWifiConfigManager.handleUserStop(user1);
3239 
3240         // Ensure that we only have 1 shared network in the database after the stop.
3241         assertEquals(1, mWifiConfigManager.getConfiguredNetworks().size());
3242         assertEquals(sharedNetwork.SSID, mWifiConfigManager.getConfiguredNetworks().get(0).SSID);
3243     }
3244 
3245     /**
3246      * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
3247      * results in a store read after bootup.
3248      */
3249     @Test
testHandleUserUnlockAfterBootup()3250     public void testHandleUserUnlockAfterBootup() throws Exception {
3251         int user1 = TEST_DEFAULT_USER;
3252 
3253         // Set up the internal data first.
3254         assertTrue(mWifiConfigManager.loadFromStore());
3255         mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
3256         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3257         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3258                 .switchUserStoresAndRead(any(List.class));
3259 
3260         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3261         // Unlock the user1 (default user) for the first time and ensure that we read the data.
3262         mWifiConfigManager.handleUserUnlock(user1);
3263         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3264         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3265                 .switchUserStoresAndRead(any(List.class));
3266         mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
3267     }
3268 
3269     /**
3270      * Verifies that the store read after bootup received after
3271      * foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)}
3272      * results in a user store read.
3273      */
3274     @Test
testHandleBootupAfterUserUnlock()3275     public void testHandleBootupAfterUserUnlock() throws Exception {
3276         int user1 = TEST_DEFAULT_USER;
3277 
3278         // Unlock the user1 (default user) for the first time and ensure that we don't read the
3279         // data.
3280         mWifiConfigManager.handleUserUnlock(user1);
3281         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3282         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3283         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3284                 .switchUserStoresAndRead(any(List.class));
3285 
3286         setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashMap<>());
3287         // Read from store now.
3288         assertTrue(mWifiConfigManager.loadFromStore());
3289         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3290                 .setUserStores(any(List.class));
3291         mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
3292     }
3293 
3294     /**
3295      * Verifies that the store read after bootup received after
3296      * a user switch via {@link WifiConfigManager#handleUserSwitch(int)}
3297      * results in a user store read.
3298      */
3299     @Test
testHandleBootupAfterUserSwitch()3300     public void testHandleBootupAfterUserSwitch() throws Exception {
3301         int user1 = TEST_DEFAULT_USER;
3302         int user2 = TEST_DEFAULT_USER + 1;
3303         setupUserProfiles(user2);
3304 
3305         // Switch from user1 to user2 and ensure that we don't read or write any data
3306         // (need to wait for loadFromStore invocation).
3307         mWifiConfigManager.handleUserSwitch(user2);
3308         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3309         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3310         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3311                 .switchUserStoresAndRead(any(List.class));
3312 
3313         // Now load from the store.
3314         assertTrue(mWifiConfigManager.loadFromStore());
3315         mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
3316 
3317         // Unlock the user2 and ensure that we read from the user store.
3318         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3319         mWifiConfigManager.handleUserUnlock(user2);
3320         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3321                 .switchUserStoresAndRead(any(List.class));
3322     }
3323 
3324     /**
3325      * Verifies that the store read after bootup received after
3326      * a previous user unlock and user switch via {@link WifiConfigManager#handleUserSwitch(int)}
3327      * results in a user store read.
3328      */
3329     @Test
testHandleBootupAfterPreviousUserUnlockAndSwitch()3330     public void testHandleBootupAfterPreviousUserUnlockAndSwitch() throws Exception {
3331         int user1 = TEST_DEFAULT_USER;
3332         int user2 = TEST_DEFAULT_USER + 1;
3333         setupUserProfiles(user2);
3334 
3335         // Unlock the user1 (default user) for the first time and ensure that we don't read the data
3336         // (need to wait for loadFromStore invocation).
3337         mWifiConfigManager.handleUserUnlock(user1);
3338         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3339         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3340         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3341                 .switchUserStoresAndRead(any(List.class));
3342 
3343         // Switch from user1 to user2 and ensure that we don't read or write any data
3344         // (need to wait for loadFromStore invocation).
3345         mWifiConfigManager.handleUserSwitch(user2);
3346         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3347         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3348         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3349                 .switchUserStoresAndRead(any(List.class));
3350 
3351         // Now load from the store.
3352         assertTrue(mWifiConfigManager.loadFromStore());
3353         mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
3354 
3355         // Unlock the user2 and ensure that we read from the user store.
3356         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3357         mWifiConfigManager.handleUserUnlock(user2);
3358         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3359                 .switchUserStoresAndRead(any(List.class));
3360     }
3361 
3362     /**
3363      * Verifies that the store read after bootup received after
3364      * a user switch and unlock of a previous user via {@link WifiConfigManager#
3365      * handleUserSwitch(int)} results in a user store read.
3366      */
3367     @Test
testHandleBootupAfterUserSwitchAndPreviousUserUnlock()3368     public void testHandleBootupAfterUserSwitchAndPreviousUserUnlock() throws Exception {
3369         int user1 = TEST_DEFAULT_USER;
3370         int user2 = TEST_DEFAULT_USER + 1;
3371         setupUserProfiles(user2);
3372 
3373         // Switch from user1 to user2 and ensure that we don't read or write any data
3374         // (need to wait for loadFromStore invocation).
3375         mWifiConfigManager.handleUserSwitch(user2);
3376         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3377         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3378         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3379                 .switchUserStoresAndRead(any(List.class));
3380 
3381         // Unlock the user1 for the first time and ensure that we don't read the data
3382         mWifiConfigManager.handleUserUnlock(user1);
3383         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
3384         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
3385         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3386                 .switchUserStoresAndRead(any(List.class));
3387 
3388         // Now load from the store.
3389         assertTrue(mWifiConfigManager.loadFromStore());
3390         mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
3391 
3392         // Unlock the user2 and ensure that we read from the user store.
3393         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3394         mWifiConfigManager.handleUserUnlock(user2);
3395         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3396                 .switchUserStoresAndRead(any(List.class));
3397     }
3398 
3399     /**
3400      * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} does
3401      * not always result in a store read unless the user had switched or just booted up.
3402      */
3403     @Test
testHandleUserUnlockWithoutSwitchOrBootup()3404     public void testHandleUserUnlockWithoutSwitchOrBootup() throws Exception {
3405         int user1 = TEST_DEFAULT_USER;
3406         int user2 = TEST_DEFAULT_USER + 1;
3407         setupUserProfiles(user2);
3408 
3409         // Set up the internal data first.
3410         assertTrue(mWifiConfigManager.loadFromStore());
3411 
3412         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3413         // user2 is unlocked and switched to foreground.
3414         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
3415         mWifiConfigManager.handleUserSwitch(user2);
3416         // Ensure that the read was invoked.
3417         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3418                 .switchUserStoresAndRead(any(List.class));
3419 
3420         // Unlock the user2 again and ensure that we don't read the data now.
3421         mWifiConfigManager.handleUserUnlock(user2);
3422         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
3423                 .switchUserStoresAndRead(any(List.class));
3424     }
3425 
3426     /**
3427      * Verifies the private network addition using
3428      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
3429      * by a non foreground user is rejected.
3430      */
3431     @Test
testAddNetworkUsingBackgroundUserUId()3432     public void testAddNetworkUsingBackgroundUserUId() throws Exception {
3433         int user2 = TEST_DEFAULT_USER + 1;
3434         setupUserProfiles(user2);
3435 
3436         int creatorUid = UserHandle.getUid(user2, 674);
3437 
3438         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(creatorUid)).thenReturn(false);
3439 
3440         // Create a network for user2 try adding it. This should be rejected.
3441         final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
3442         NetworkUpdateResult result = addNetworkToWifiConfigManager(user2Network, creatorUid);
3443         assertFalse(result.isSuccess());
3444     }
3445 
3446     /**
3447      * Verifies the private network addition using
3448      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
3449      * by SysUI is always accepted.
3450      */
3451     @Test
testAddNetworkUsingSysUiUid()3452     public void testAddNetworkUsingSysUiUid() throws Exception {
3453         // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile|
3454         int user2 = TEST_DEFAULT_USER + 1;
3455         setupUserProfiles(user2);
3456 
3457         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(false);
3458         mWifiConfigManager.handleUserSwitch(user2);
3459 
3460         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(TEST_SYSUI_UID)).thenReturn(true);
3461 
3462         // Create a network for user2 try adding it. This should be rejected.
3463         final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
3464         NetworkUpdateResult result = addNetworkToWifiConfigManager(user2Network, TEST_SYSUI_UID);
3465         assertTrue(result.isSuccess());
3466     }
3467 
3468     /**
3469      * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()}
3470      * attempts to read from the stores even when the store files are not present.
3471      */
3472     @Test
testFreshInstallLoadFromStore()3473     public void testFreshInstallLoadFromStore() throws Exception {
3474         assertTrue(mWifiConfigManager.loadFromStore());
3475 
3476         verify(mWifiConfigStore).read();
3477 
3478         assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
3479     }
3480 
3481     /**
3482      * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()}
3483      * attempts to read from the stores even if the store files are not present and the
3484      * user unlock already comes in.
3485      */
3486     @Test
testFreshInstallLoadFromStoreAfterUserUnlock()3487     public void testFreshInstallLoadFromStoreAfterUserUnlock() throws Exception {
3488         int user1 = TEST_DEFAULT_USER;
3489 
3490         // Unlock the user1 (default user) for the first time and ensure that we don't read the
3491         // data.
3492         mWifiConfigManager.handleUserUnlock(user1);
3493         verify(mWifiConfigStore, never()).read();
3494 
3495         // Read from store now.
3496         assertTrue(mWifiConfigManager.loadFromStore());
3497 
3498         // Ensure that the read was invoked.
3499         verify(mWifiConfigStore).read();
3500     }
3501 
3502     /**
3503      * Verifies the user switch using {@link WifiConfigManager#handleUserSwitch(int)} is handled
3504      * when the store files (new or legacy) are not present.
3505      */
3506     @Test
testHandleUserSwitchAfterFreshInstall()3507     public void testHandleUserSwitchAfterFreshInstall() throws Exception {
3508         int user2 = TEST_DEFAULT_USER + 1;
3509 
3510         assertTrue(mWifiConfigManager.loadFromStore());
3511         verify(mWifiConfigStore).read();
3512 
3513         setupStoreDataForUserRead(new ArrayList<>(), new HashMap<>());
3514         // Now switch the user to user 2.
3515         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(user2))).thenReturn(true);
3516         mWifiConfigManager.handleUserSwitch(user2);
3517         // Ensure that the read was invoked.
3518         mContextConfigStoreMockOrder.verify(mWifiConfigStore)
3519                 .switchUserStoresAndRead(any(List.class));
3520     }
3521 
3522     /**
3523      * Verifies that the last user selected network parameter is set when
3524      * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set
3525      * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or
3526      * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID.
3527      */
3528     @Test
testLastSelectedNetwork()3529     public void testLastSelectedNetwork() throws Exception {
3530         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
3531         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
3532 
3533         when(mClock.getElapsedSinceBootMillis()).thenReturn(67L);
3534         assertTrue(mWifiConfigManager.enableNetwork(
3535                 result.getNetworkId(), true, TEST_CREATOR_UID, TEST_CREATOR_NAME));
3536         assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
3537         assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp());
3538 
3539         // Now disable the network and ensure that the last selected flag is cleared.
3540         assertTrue(mWifiConfigManager.disableNetwork(
3541                 result.getNetworkId(), TEST_CREATOR_UID, TEST_CREATOR_NAME));
3542         assertEquals(
3543                 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
3544 
3545         // Enable it again and remove the network to ensure that the last selected flag was cleared.
3546         assertTrue(mWifiConfigManager.enableNetwork(
3547                 result.getNetworkId(), true, TEST_CREATOR_UID, TEST_CREATOR_NAME));
3548         assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
3549         assertEquals(openNetwork.getKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey());
3550 
3551         assertTrue(mWifiConfigManager.removeNetwork(
3552                 result.getNetworkId(), TEST_CREATOR_UID, TEST_CREATOR_NAME));
3553         assertEquals(
3554                 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
3555     }
3556 
3557     /**
3558      * Verifies that all the networks for the provided app is removed when
3559      * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked.
3560      */
3561     @Test
testRemoveNetworksForApp()3562     public void testRemoveNetworksForApp() throws Exception {
3563         when(mPackageManager.getNameForUid(TEST_CREATOR_UID)).thenReturn(TEST_CREATOR_NAME);
3564 
3565         verifyRemoveNetworksForApp();
3566     }
3567 
3568     /**
3569      * Verifies that all the networks for the provided app is removed when
3570      * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked.
3571      */
3572     @Test
testRemoveNetworksForAppUsingSharedUid()3573     public void testRemoveNetworksForAppUsingSharedUid() throws Exception {
3574         when(mPackageManager.getNameForUid(TEST_CREATOR_UID))
3575                 .thenReturn(TEST_CREATOR_NAME + ":" + TEST_CREATOR_UID);
3576 
3577         verifyRemoveNetworksForApp();
3578     }
3579 
3580     /**
3581      * Verifies that all the networks for the provided user is removed when
3582      * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked.
3583      */
3584     @Test
testRemoveNetworksForUser()3585     public void testRemoveNetworksForUser() throws Exception {
3586         verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
3587         verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
3588         verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
3589 
3590         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
3591 
3592         assertEquals(3, mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER).size());
3593 
3594         // Ensure all the networks are removed now.
3595         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
3596     }
3597 
3598     /**
3599      * Verifies that the connect choice is removed from all networks when
3600      * {@link WifiConfigManager#removeNetwork(int, int)} is invoked.
3601      */
3602     @Test
testRemoveNetworkRemovesConnectChoice()3603     public void testRemoveNetworkRemovesConnectChoice() throws Exception {
3604         WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
3605         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
3606         WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
3607         verifyAddNetworkToWifiConfigManager(network1);
3608         verifyAddNetworkToWifiConfigManager(network2);
3609         verifyAddNetworkToWifiConfigManager(network3);
3610 
3611         // Set connect choice of network 2 over network 1.
3612         assertTrue(
3613                 mWifiConfigManager.setNetworkConnectChoice(
3614                         network1.networkId, network2.getKey()));
3615 
3616         WifiConfiguration retrievedNetwork =
3617                 mWifiConfigManager.getConfiguredNetwork(network1.networkId);
3618         assertEquals(
3619                 network2.getKey(),
3620                 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
3621 
3622         // Remove network 3 and ensure that the connect choice on network 1 is not removed.
3623         assertTrue(mWifiConfigManager.removeNetwork(
3624                 network3.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
3625         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
3626         assertEquals(
3627                 network2.getKey(),
3628                 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
3629 
3630         // Now remove network 2 and ensure that the connect choice on network 1 is removed..
3631         assertTrue(mWifiConfigManager.removeNetwork(
3632                 network2.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
3633         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
3634         assertNotEquals(
3635                 network2.getKey(),
3636                 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
3637 
3638         // This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for
3639         // clearing it after network removal.
3640         mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(eq(false));
3641     }
3642 
3643     /**
3644      * Disabling autojoin should clear associated connect choice links.
3645      */
3646     @Test
testDisableAutojoinRemovesConnectChoice()3647     public void testDisableAutojoinRemovesConnectChoice() throws Exception {
3648         WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
3649         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
3650         WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
3651         verifyAddNetworkToWifiConfigManager(network1);
3652         verifyAddNetworkToWifiConfigManager(network2);
3653         verifyAddNetworkToWifiConfigManager(network3);
3654 
3655         // Set connect choice of network 2 over network 1 and network 3.
3656         assertTrue(
3657                 mWifiConfigManager.setNetworkConnectChoice(
3658                         network1.networkId, network2.getKey()));
3659         assertTrue(
3660                 mWifiConfigManager.setNetworkConnectChoice(
3661                         network3.networkId, network2.getKey()));
3662 
3663         WifiConfiguration retrievedNetwork =
3664                 mWifiConfigManager.getConfiguredNetwork(network3.networkId);
3665         assertEquals(
3666                 network2.getKey(),
3667                 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
3668 
3669         // Disable network 3
3670         assertTrue(mWifiConfigManager.allowAutojoin(network3.networkId, false));
3671         // Ensure that the connect choice on network 3 is removed.
3672         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network3.networkId);
3673         assertEquals(
3674                 null,
3675                 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
3676         // Ensure that the connect choice on network 1 is not removed.
3677         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
3678         assertEquals(
3679                 network2.getKey(),
3680                 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
3681     }
3682 
3683     /**
3684      * Verifies that all the ephemeral and passpoint networks are removed when
3685      * {@link WifiConfigManager#removeAllEphemeralOrPasspointConfiguredNetworks()} is invoked.
3686      */
3687     @Test
testRemoveAllEphemeralOrPasspointConfiguredNetworks()3688     public void testRemoveAllEphemeralOrPasspointConfiguredNetworks() throws Exception {
3689         WifiConfiguration savedOpenNetwork = WifiConfigurationTestUtil.createOpenNetwork();
3690         WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createEphemeralNetwork();
3691         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
3692 
3693         verifyAddNetworkToWifiConfigManager(savedOpenNetwork);
3694         verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork);
3695         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
3696 
3697         List<WifiConfiguration> expectedConfigsBeforeRemove = new ArrayList<WifiConfiguration>() {{
3698                 add(savedOpenNetwork);
3699                 add(ephemeralNetwork);
3700                 add(passpointNetwork);
3701             }};
3702         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3703                 expectedConfigsBeforeRemove, mWifiConfigManager.getConfiguredNetworks());
3704 
3705         assertTrue(mWifiConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks());
3706 
3707         List<WifiConfiguration> expectedConfigsAfterRemove = new ArrayList<WifiConfiguration>() {{
3708                 add(savedOpenNetwork);
3709             }};
3710         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3711                 expectedConfigsAfterRemove, mWifiConfigManager.getConfiguredNetworks());
3712 
3713         // No more ephemeral or passpoint networks to remove now.
3714         assertFalse(mWifiConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks());
3715     }
3716 
3717     /**
3718      * Verifies that Passpoint network corresponding with given config key (FQDN) is removed.
3719      *
3720      * @throws Exception
3721      */
3722     @Test
testRemovePasspointConfiguredNetwork()3723     public void testRemovePasspointConfiguredNetwork() throws Exception {
3724         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
3725         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
3726 
3727         assertTrue(mWifiConfigManager.removePasspointConfiguredNetwork(
3728                 passpointNetwork.getKey()));
3729     }
3730 
3731     /**
3732      * Verifies that suggested network corresponding with given config key is removed.
3733      *
3734      * @throws Exception
3735      */
3736     @Test
testRemoveSuggestionConfiguredNetwork()3737     public void testRemoveSuggestionConfiguredNetwork() throws Exception {
3738         WifiConfiguration suggestedNetwork = WifiConfigurationTestUtil.createEphemeralNetwork();
3739         suggestedNetwork.fromWifiNetworkSuggestion = true;
3740         verifyAddEphemeralNetworkToWifiConfigManager(suggestedNetwork);
3741 
3742         assertTrue(mWifiConfigManager.removeSuggestionConfiguredNetwork(
3743                 suggestedNetwork.getKey()));
3744     }
3745 
3746     /**
3747      * Verifies that the modification of a single network using
3748      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any
3749      * updates to the network config in
3750      * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected
3751      * in the internal database.
3752      */
3753     @Test
testUpdateSingleNetworkWithKeysUpdate()3754     public void testUpdateSingleNetworkWithKeysUpdate() {
3755         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
3756         network.enterpriseConfig =
3757                 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
3758         verifyAddNetworkToWifiConfigManager(network);
3759 
3760         // Now verify that network configurations match before we make any change.
3761         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3762                 network,
3763                 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
3764 
3765         // Modify the network ca_cert field in updateNetworkKeys method during a network
3766         // config update.
3767         final String newCaCertAlias = "test";
3768         assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias());
3769 
3770         doAnswer(new AnswerWithArguments() {
3771             public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) {
3772                 newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
3773                 return true;
3774             }
3775         }).when(mWifiKeyStore).updateNetworkKeys(
3776                 any(WifiConfiguration.class), any(WifiConfiguration.class));
3777 
3778         verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
3779 
3780         // Now verify that the keys update is reflected in the configuration fetched from internal
3781         // db.
3782         network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
3783         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3784                 network,
3785                 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
3786     }
3787 
3788     /**
3789      * Verifies that the dump method prints out all the saved network details with passwords masked.
3790      * {@link WifiConfigManager#dump(FileDescriptor, PrintWriter, String[])}.
3791      */
3792     @Test
testDump()3793     public void testDump() {
3794         WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
3795         WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
3796         eapNetwork.enterpriseConfig.setPassword("blah");
3797 
3798         verifyAddNetworkToWifiConfigManager(pskNetwork);
3799         verifyAddNetworkToWifiConfigManager(eapNetwork);
3800 
3801         StringWriter stringWriter = new StringWriter();
3802         mWifiConfigManager.dump(
3803                 new FileDescriptor(), new PrintWriter(stringWriter), new String[0]);
3804         String dumpString = stringWriter.toString();
3805 
3806         // Ensure that the network SSIDs were dumped out.
3807         assertTrue(dumpString.contains(pskNetwork.SSID));
3808         assertTrue(dumpString.contains(eapNetwork.SSID));
3809 
3810         // Ensure that the network passwords were not dumped out.
3811         assertFalse(dumpString.contains(pskNetwork.preSharedKey));
3812         assertFalse(dumpString.contains(eapNetwork.enterpriseConfig.getPassword()));
3813     }
3814 
3815     /**
3816      * Verifies the ordering of network list generated using
3817      * {@link WifiConfigManager#retrieveHiddenNetworkList()}.
3818      */
3819     @Test
testRetrieveHiddenList()3820     public void testRetrieveHiddenList() {
3821         // Create and add 3 networks.
3822         WifiConfiguration network1 = WifiConfigurationTestUtil.createWepHiddenNetwork();
3823         WifiConfiguration network2 = WifiConfigurationTestUtil.createPskHiddenNetwork();
3824         WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork();
3825         verifyAddNetworkToWifiConfigManager(network1);
3826         verifyAddNetworkToWifiConfigManager(network2);
3827         verifyAddNetworkToWifiConfigManager(network3);
3828         mWifiConfigManager.updateNetworkAfterConnect(network3.networkId);
3829 
3830         // Now set scan results of network2 to set the corresponding
3831         // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field.
3832         assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(network2.networkId,
3833                 createScanDetailForNetwork(network2).getScanResult(), 54));
3834 
3835         // Retrieve the hidden network list & verify the order of the networks returned.
3836         List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks =
3837                 mWifiConfigManager.retrieveHiddenNetworkList();
3838         assertEquals(3, hiddenNetworks.size());
3839         assertEquals(network3.SSID, hiddenNetworks.get(0).ssid);
3840         assertEquals(network2.SSID, hiddenNetworks.get(1).ssid);
3841         assertEquals(network1.SSID, hiddenNetworks.get(2).ssid);
3842     }
3843 
3844     /**
3845      * Verifies the addition of network configurations using
3846      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and
3847      * default key mgmt does not add duplicate network configs.
3848      */
3849     @Test
testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt()3850     public void testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt() {
3851         final String ssid = "\"test_blah\"";
3852         // Add a network with the above SSID and default key mgmt and ensure it was added
3853         // successfully.
3854         WifiConfiguration network1 = new WifiConfiguration();
3855         network1.SSID = ssid;
3856         NetworkUpdateResult result = addNetworkToWifiConfigManager(network1);
3857         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3858         assertTrue(result.isNewNetwork());
3859 
3860         List<WifiConfiguration> retrievedNetworks =
3861                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
3862         assertEquals(1, retrievedNetworks.size());
3863         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3864                 network1, retrievedNetworks.get(0));
3865 
3866         // Now add a second network with the same SSID and default key mgmt and ensure that it
3867         // didn't add a new duplicate network.
3868         WifiConfiguration network2 = new WifiConfiguration();
3869         network2.SSID = ssid;
3870         result = addNetworkToWifiConfigManager(network2);
3871         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3872         assertFalse(result.isNewNetwork());
3873 
3874         retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
3875         assertEquals(1, retrievedNetworks.size());
3876         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3877                 network2, retrievedNetworks.get(0));
3878     }
3879 
3880     /**
3881      * Verifies the addition of network configurations using
3882      * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and
3883      * different key mgmt should add different network configs.
3884      */
3885     @Test
testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt()3886     public void testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt() {
3887         final String ssid = "\"test_blah\"";
3888         // Add a network with the above SSID and WPA_PSK key mgmt and ensure it was added
3889         // successfully.
3890         WifiConfiguration network1 = new WifiConfiguration();
3891         network1.SSID = ssid;
3892         network1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
3893         network1.preSharedKey = "\"test_blah\"";
3894         NetworkUpdateResult result = addNetworkToWifiConfigManager(network1);
3895         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3896         assertTrue(result.isNewNetwork());
3897 
3898         List<WifiConfiguration> retrievedNetworks =
3899                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
3900         assertEquals(1, retrievedNetworks.size());
3901         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
3902                 network1, retrievedNetworks.get(0));
3903 
3904         // Now add a second network with the same SSID and NONE key mgmt and ensure that it
3905         // does add a new network.
3906         WifiConfiguration network2 = new WifiConfiguration();
3907         network2.SSID = ssid;
3908         network2.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
3909         result = addNetworkToWifiConfigManager(network2);
3910         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
3911         assertTrue(result.isNewNetwork());
3912 
3913         retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
3914         assertEquals(2, retrievedNetworks.size());
3915         List<WifiConfiguration> networks = Arrays.asList(network1, network2);
3916         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
3917                 networks, retrievedNetworks);
3918     }
3919 
3920     /**
3921      * Verifies that adding a network with a proxy, without having permission OVERRIDE_WIFI_CONFIG,
3922      * holding device policy, or profile owner policy fails.
3923      */
3924     @Test
testAddNetworkWithProxyFails()3925     public void testAddNetworkWithProxyFails() {
3926         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3927                 false, // withNetworkSettings
3928                 false, // withProfileOwnerPolicy
3929                 false, // withDeviceOwnerPolicy
3930                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
3931                 false, // assertSuccess
3932                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3933         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3934                 false, // withNetworkSettings
3935                 false, // withProfileOwnerPolicy
3936                 false, // withDeviceOwnerPolicy
3937                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
3938                 false, // assertSuccess
3939                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3940     }
3941 
3942     /**
3943      * Verifies that adding a network with a PAC or STATIC proxy with permission
3944      * OVERRIDE_WIFI_CONFIG is successful
3945      */
3946     @Test
testAddNetworkWithProxyWithConfOverride()3947     public void testAddNetworkWithProxyWithConfOverride() {
3948         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3949                 true,  // withNetworkSettings
3950                 false, // withProfileOwnerPolicy
3951                 false, // withDeviceOwnerPolicy
3952                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
3953                 true, // assertSuccess
3954                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3955         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3956                 true,  // withNetworkSettings
3957                 false, // withProfileOwnerPolicy
3958                 false, // withDeviceOwnerPolicy
3959                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
3960                 true, // assertSuccess
3961                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3962     }
3963 
3964     /**
3965      * Verifies that adding a network with a PAC or STATIC proxy, while holding policy
3966      * {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER} is successful
3967      */
3968     @Test
testAddNetworkWithProxyAsProfileOwner()3969     public void testAddNetworkWithProxyAsProfileOwner() {
3970         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3971                 false,  // withNetworkSettings
3972                 true, // withProfileOwnerPolicy
3973                 false, // withDeviceOwnerPolicy
3974                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
3975                 true, // assertSuccess
3976                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3977         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3978                 false,  // withNetworkSettings
3979                 true, // withProfileOwnerPolicy
3980                 false, // withDeviceOwnerPolicy
3981                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
3982                 true, // assertSuccess
3983                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3984     }
3985     /**
3986      * Verifies that adding a network with a PAC or STATIC proxy, while holding policy
3987      * {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER} is successful
3988      */
3989     @Test
testAddNetworkWithProxyAsDeviceOwner()3990     public void testAddNetworkWithProxyAsDeviceOwner() {
3991         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3992                 false,  // withNetworkSettings
3993                 false, // withProfileOwnerPolicy
3994                 true, // withDeviceOwnerPolicy
3995                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
3996                 true, // assertSuccess
3997                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
3998         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
3999                 false,  // withNetworkSettings
4000                 false, // withProfileOwnerPolicy
4001                 true, // withDeviceOwnerPolicy
4002                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
4003                 true, // assertSuccess
4004                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4005     }
4006 
4007     /**
4008      * Verifies that adding a network with a PAC or STATIC proxy, while having the
4009      * {@link android.Manifest.permission#NETWORK_MANAGED_PROVISIONING} permission is successful
4010      */
4011     @Test
testAddNetworkWithProxyWithNetworkManagedPermission()4012     public void testAddNetworkWithProxyWithNetworkManagedPermission() {
4013         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4014                 false, // withNetworkSettings
4015                 false, // withNetworkSetupWizard
4016                 true, // withNetworkManagedProvisioning
4017                 false, // withProfileOwnerPolicy
4018                 false, // withDeviceOwnerPolicy
4019                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
4020                 true, // assertSuccess
4021                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4022         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4023                 false,  // withNetworkSettings
4024                 false, // withNetworkSetupWizard
4025                 true, // withNetworkManagedProvisioning
4026                 false, // withProfileOwnerPolicy
4027                 false, // withDeviceOwnerPolicy
4028                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
4029                 true, // assertSuccess
4030                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4031     }
4032 
4033     /**
4034      * Verifies that updating a network (that has no proxy) and adding a PAC or STATIC proxy fails
4035      * without being able to override configs, or holding Device or Profile owner policies.
4036      */
4037     @Test
testUpdateNetworkAddProxyFails()4038     public void testUpdateNetworkAddProxyFails() {
4039         WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
4040         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
4041         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4042                 false, // withNetworkSettings
4043                 false, // withProfileOwnerPolicy
4044                 false, // withDeviceOwnerPolicy
4045                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
4046                 false, // assertSuccess
4047                 result.getNetworkId()); // Update networkID
4048         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4049                 false, // withNetworkSettings
4050                 false, // withProfileOwnerPolicy
4051                 false, // withDeviceOwnerPolicy
4052                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(),
4053                 false, // assertSuccess
4054                 result.getNetworkId()); // Update networkID
4055     }
4056     /**
4057      * Verifies that updating a network and adding a proxy is successful in the cases where app can
4058      * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
4059      * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
4060      * otherwise.
4061      */
4062     @Test
testUpdateNetworkAddProxyWithPermissionAndSystem()4063     public void testUpdateNetworkAddProxyWithPermissionAndSystem() {
4064         // Testing updating network with uid permission OVERRIDE_WIFI_CONFIG
4065         WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
4066         NetworkUpdateResult result = addNetworkToWifiConfigManager(network, TEST_CREATOR_UID);
4067         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4068         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4069                 true, // withNetworkSettings
4070                 false, // withProfileOwnerPolicy
4071                 false, // withDeviceOwnerPolicy
4072                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
4073                 true, // assertSuccess
4074                 result.getNetworkId()); // Update networkID
4075 
4076         network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
4077         result = addNetworkToWifiConfigManager(network, TEST_CREATOR_UID);
4078         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4079         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4080                 false, // withNetworkSettings
4081                 true, // withNetworkSetupWizard
4082                 false, false, // withProfileOwnerPolicy
4083                 false, // withDeviceOwnerPolicy
4084                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
4085                 true, // assertSuccess
4086                 result.getNetworkId()); // Update networkID
4087 
4088         // Testing updating network with proxy while holding Profile Owner policy
4089         network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
4090         result = addNetworkToWifiConfigManager(network, TEST_NO_PERM_UID);
4091         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4092         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4093                 false, // withNetworkSettings
4094                 true, // withProfileOwnerPolicy
4095                 false, // withDeviceOwnerPolicy
4096                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
4097                 true, // assertSuccess
4098                 result.getNetworkId()); // Update networkID
4099 
4100         // Testing updating network with proxy while holding Device Owner Policy
4101         network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
4102         result = addNetworkToWifiConfigManager(network, TEST_NO_PERM_UID);
4103         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4104         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4105                 false, // withNetworkSettings
4106                 false, // withProfileOwnerPolicy
4107                 true, // withDeviceOwnerPolicy
4108                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(),
4109                 true, // assertSuccess
4110                 result.getNetworkId()); // Update networkID
4111     }
4112 
4113     /**
4114      * Verifies that updating a network that has a proxy without changing the proxy, can succeed
4115      * without proxy specific permissions.
4116      */
4117     @Test
testUpdateNetworkUnchangedProxy()4118     public void testUpdateNetworkUnchangedProxy() {
4119         IpConfiguration ipConf = WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy();
4120         // First create a WifiConfiguration with proxy
4121         NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4122                         false, // withNetworkSettings
4123                         true, // withProfileOwnerPolicy
4124                         false, // withDeviceOwnerPolicy
4125                         ipConf,
4126                         true, // assertSuccess
4127                         WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4128         // Update the network while using the same ipConf, and no proxy specific permissions
4129         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4130                         false, // withNetworkSettings
4131                         false, // withProfileOwnerPolicy
4132                         false, // withDeviceOwnerPolicy
4133                         ipConf,
4134                         true, // assertSuccess
4135                         result.getNetworkId()); // Update networkID
4136     }
4137 
4138     /**
4139      * Verifies that updating a network with a different proxy succeeds in the cases where app can
4140      * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
4141      * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
4142      * otherwise.
4143      */
4144     @Test
testUpdateNetworkDifferentProxy()4145     public void testUpdateNetworkDifferentProxy() {
4146         // Create two proxy configurations of the same type, but different values
4147         IpConfiguration ipConf1 =
4148                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
4149                         WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
4150                         TEST_STATIC_PROXY_HOST_1,
4151                         TEST_STATIC_PROXY_PORT_1,
4152                         TEST_STATIC_PROXY_EXCLUSION_LIST_1,
4153                         TEST_PAC_PROXY_LOCATION_1);
4154         IpConfiguration ipConf2 =
4155                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
4156                         WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
4157                         TEST_STATIC_PROXY_HOST_2,
4158                         TEST_STATIC_PROXY_PORT_2,
4159                         TEST_STATIC_PROXY_EXCLUSION_LIST_2,
4160                         TEST_PAC_PROXY_LOCATION_2);
4161 
4162         // Update with Conf Override
4163         NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4164                 true, // withNetworkSettings
4165                 false, // withProfileOwnerPolicy
4166                 false, // withDeviceOwnerPolicy
4167                 ipConf1,
4168                 true, // assertSuccess
4169                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4170         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4171                 true, // withNetworkSettings
4172                 false, // withProfileOwnerPolicy
4173                 false, // withDeviceOwnerPolicy
4174                 ipConf2,
4175                 true, // assertSuccess
4176                 result.getNetworkId()); // Update networkID
4177 
4178         // Update as Device Owner
4179         result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4180                 false, // withNetworkSettings
4181                 false, // withProfileOwnerPolicy
4182                 true, // withDeviceOwnerPolicy
4183                 ipConf1,
4184                 true, // assertSuccess
4185                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4186         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4187                 false, // withNetworkSettings
4188                 false, // withProfileOwnerPolicy
4189                 true, // withDeviceOwnerPolicy
4190                 ipConf2,
4191                 true, // assertSuccess
4192                 result.getNetworkId()); // Update networkID
4193 
4194         // Update as Profile Owner
4195         result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4196                 false, // withNetworkSettings
4197                 true, // withProfileOwnerPolicy
4198                 false, // withDeviceOwnerPolicy
4199                 ipConf1,
4200                 true, // assertSuccess
4201                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4202         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4203                 false, // withNetworkSettings
4204                 true, // withProfileOwnerPolicy
4205                 false, // withDeviceOwnerPolicy
4206                 ipConf2,
4207                 true, // assertSuccess
4208                 result.getNetworkId()); // Update networkID
4209 
4210         // Update with no permissions (should fail)
4211         result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4212                 false, // withNetworkSettings
4213                 true, // withProfileOwnerPolicy
4214                 false, // withDeviceOwnerPolicy
4215                 ipConf1,
4216                 true, // assertSuccess
4217                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4218         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4219                 false, // withNetworkSettings
4220                 false, // withProfileOwnerPolicy
4221                 false, // withDeviceOwnerPolicy
4222                 ipConf2,
4223                 false, // assertSuccess
4224                 result.getNetworkId()); // Update networkID
4225     }
4226     /**
4227      * Verifies that updating a network removing its proxy succeeds in the cases where app can
4228      * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER},
4229      * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails
4230      * otherwise.
4231      */
4232     @Test
testUpdateNetworkRemoveProxy()4233     public void testUpdateNetworkRemoveProxy() {
4234         // Create two different IP configurations, one with a proxy and another without.
4235         IpConfiguration ipConf1 =
4236                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
4237                         WifiConfigurationTestUtil.STATIC_PROXY_SETTING,
4238                         TEST_STATIC_PROXY_HOST_1,
4239                         TEST_STATIC_PROXY_PORT_1,
4240                         TEST_STATIC_PROXY_EXCLUSION_LIST_1,
4241                         TEST_PAC_PROXY_LOCATION_1);
4242         IpConfiguration ipConf2 =
4243                 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy(
4244                         WifiConfigurationTestUtil.NONE_PROXY_SETTING,
4245                         TEST_STATIC_PROXY_HOST_2,
4246                         TEST_STATIC_PROXY_PORT_2,
4247                         TEST_STATIC_PROXY_EXCLUSION_LIST_2,
4248                         TEST_PAC_PROXY_LOCATION_2);
4249 
4250         // Update with Conf Override
4251         NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4252                 true, // withNetworkSettings
4253                 false, // withProfileOwnerPolicy
4254                 false, // withDeviceOwnerPolicy
4255                 ipConf1,
4256                 true, // assertSuccess
4257                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4258         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4259                 true, // withNetworkSettings
4260                 false, // withProfileOwnerPolicy
4261                 false, // withDeviceOwnerPolicy
4262                 ipConf2,
4263                 true, // assertSuccess
4264                 result.getNetworkId()); // Update networkID
4265 
4266         // Update as Device Owner
4267         result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4268                 false, // withNetworkSettings
4269                 false, // withProfileOwnerPolicy
4270                 true, // withDeviceOwnerPolicy
4271                 ipConf1,
4272                 true, // assertSuccess
4273                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4274         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4275                 false, // withNetworkSettings
4276                 false, // withProfileOwnerPolicy
4277                 true, // withDeviceOwnerPolicy
4278                 ipConf2,
4279                 true, // assertSuccess
4280                 result.getNetworkId()); // Update networkID
4281 
4282         // Update as Profile Owner
4283         result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4284                 false, // withNetworkSettings
4285                 true, // withProfileOwnerPolicy
4286                 false, // withDeviceOwnerPolicy
4287                 ipConf1,
4288                 true, // assertSuccess
4289                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4290         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4291                 false, // withNetworkSettings
4292                 true, // withProfileOwnerPolicy
4293                 false, // withDeviceOwnerPolicy
4294                 ipConf2,
4295                 true, // assertSuccess
4296                 result.getNetworkId()); // Update networkID
4297 
4298         // Update with no permissions (should fail)
4299         result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4300                 false, // withNetworkSettings
4301                 true, // withProfileOwnerPolicy
4302                 false, // withDeviceOwnerPolicy
4303                 ipConf1,
4304                 true, // assertSuccess
4305                 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID
4306         verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4307                 false, // withNetworkSettings
4308                 false, // withProfileOwnerPolicy
4309                 false, // withDeviceOwnerPolicy
4310                 ipConf2,
4311                 false, // assertSuccess
4312                 result.getNetworkId()); // Update networkID
4313     }
4314 
4315     /**
4316      * Verifies that the app specified BSSID is converted and saved in lower case.
4317      */
4318     @Test
testAppSpecifiedBssidIsSavedInLowerCase()4319     public void testAppSpecifiedBssidIsSavedInLowerCase() {
4320         final String bssid = "0A:08:5C:BB:89:6D"; // upper case
4321         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
4322         openNetwork.BSSID = bssid;
4323 
4324         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
4325 
4326         WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(
4327                 result.getNetworkId());
4328 
4329         assertNotEquals(retrievedNetwork.BSSID, bssid);
4330         assertEquals(retrievedNetwork.BSSID, bssid.toLowerCase());
4331     }
4332 
4333     /**
4334      * Verifies that the method resetSimNetworks updates SIM presence status and SIM configs.
4335      */
4336     @Test
testResetSimNetworks()4337     public void testResetSimNetworks() {
4338         String expectedIdentity = "13214561234567890@wlan.mnc456.mcc321.3gppnetwork.org";
4339         when(mDataTelephonyManager.getSubscriberId()).thenReturn("3214561234567890");
4340         when(mDataTelephonyManager.getSimState()).thenReturn(TelephonyManager.SIM_STATE_READY);
4341         when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
4342         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
4343         List<SubscriptionInfo> subList = new ArrayList<>() {{
4344                 add(mock(SubscriptionInfo.class));
4345             }};
4346         when(mSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(subList);
4347         when(mSubscriptionManager.getActiveSubscriptionIdList())
4348                 .thenReturn(new int[]{DATA_SUBID});
4349 
4350         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
4351         WifiConfiguration simNetwork = WifiConfigurationTestUtil.createEapNetwork(
4352                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
4353         WifiConfiguration peapSimNetwork = WifiConfigurationTestUtil.createEapNetwork(
4354                 WifiEnterpriseConfig.Eap.PEAP, WifiEnterpriseConfig.Phase2.SIM);
4355         network.enterpriseConfig.setIdentity("identity1");
4356         network.enterpriseConfig.setAnonymousIdentity("anonymous_identity1");
4357         simNetwork.enterpriseConfig.setIdentity("identity2");
4358         simNetwork.enterpriseConfig.setAnonymousIdentity("anonymous_identity2");
4359         peapSimNetwork.enterpriseConfig.setIdentity("identity3");
4360         peapSimNetwork.enterpriseConfig.setAnonymousIdentity("anonymous_identity3");
4361         verifyAddNetworkToWifiConfigManager(network);
4362         verifyAddNetworkToWifiConfigManager(simNetwork);
4363         verifyAddNetworkToWifiConfigManager(peapSimNetwork);
4364         MockitoSession mockSession = ExtendedMockito.mockitoSession()
4365                 .mockStatic(SubscriptionManager.class)
4366                 .startMocking();
4367         when(SubscriptionManager.getDefaultDataSubscriptionId()).thenReturn(DATA_SUBID);
4368         when(SubscriptionManager.isValidSubscriptionId(anyInt())).thenReturn(true);
4369 
4370         // SIM was removed, resetting SIM Networks
4371         mWifiConfigManager.resetSimNetworks();
4372 
4373         // Verify SIM configs are reset and non-SIM configs are not changed.
4374         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
4375                 network,
4376                 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
4377         WifiConfiguration retrievedSimNetwork =
4378                 mWifiConfigManager.getConfiguredNetwork(simNetwork.networkId);
4379         assertEquals("", retrievedSimNetwork.enterpriseConfig.getAnonymousIdentity());
4380         assertEquals("", retrievedSimNetwork.enterpriseConfig.getIdentity());
4381         WifiConfiguration retrievedPeapSimNetwork =
4382                 mWifiConfigManager.getConfiguredNetwork(peapSimNetwork.networkId);
4383         assertEquals(expectedIdentity, retrievedPeapSimNetwork.enterpriseConfig.getIdentity());
4384         assertNotEquals("", retrievedPeapSimNetwork.enterpriseConfig.getAnonymousIdentity());
4385 
4386         mockSession.finishMocking();
4387     }
4388 
4389     /**
4390      * {@link WifiConfigManager#resetSimNetworks()} should reset all non-PEAP SIM networks, no
4391      * matter if {@link WifiCarrierInfoManager#getSimIdentity()} returns null or not.
4392      */
4393     @Test
testResetSimNetworks_getSimIdentityNull_shouldResetAllNonPeapSimIdentities()4394     public void testResetSimNetworks_getSimIdentityNull_shouldResetAllNonPeapSimIdentities() {
4395         when(mDataTelephonyManager.getSubscriberId()).thenReturn("");
4396         when(mDataTelephonyManager.getSimState()).thenReturn(TelephonyManager.SIM_STATE_READY);
4397         when(mDataTelephonyManager.getSimOperator()).thenReturn("");
4398         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
4399         List<SubscriptionInfo> subList = new ArrayList<>() {{
4400                 add(mock(SubscriptionInfo.class));
4401             }};
4402         when(mSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(subList);
4403         when(mSubscriptionManager.getActiveSubscriptionIdList())
4404                 .thenReturn(new int[]{DATA_SUBID});
4405 
4406         WifiConfiguration peapSimNetwork = WifiConfigurationTestUtil.createEapNetwork(
4407                 WifiEnterpriseConfig.Eap.PEAP, WifiEnterpriseConfig.Phase2.SIM);
4408         peapSimNetwork.enterpriseConfig.setIdentity("identity_peap");
4409         peapSimNetwork.enterpriseConfig.setAnonymousIdentity("anonymous_identity_peap");
4410         verifyAddNetworkToWifiConfigManager(peapSimNetwork);
4411 
4412         WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
4413         network.enterpriseConfig.setIdentity("identity");
4414         network.enterpriseConfig.setAnonymousIdentity("anonymous_identity");
4415         verifyAddNetworkToWifiConfigManager(network);
4416 
4417         WifiConfiguration simNetwork = WifiConfigurationTestUtil.createEapNetwork(
4418                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
4419         simNetwork.enterpriseConfig.setIdentity("identity_eap_sim");
4420         simNetwork.enterpriseConfig.setAnonymousIdentity("anonymous_identity_eap_sim");
4421         verifyAddNetworkToWifiConfigManager(simNetwork);
4422         MockitoSession mockSession = ExtendedMockito.mockitoSession()
4423                 .mockStatic(SubscriptionManager.class)
4424                 .startMocking();
4425         when(SubscriptionManager.getDefaultDataSubscriptionId()).thenReturn(DATA_SUBID);
4426         when(SubscriptionManager.isValidSubscriptionId(anyInt())).thenReturn(true);
4427 
4428         // SIM was removed, resetting SIM Networks
4429         mWifiConfigManager.resetSimNetworks();
4430 
4431         // EAP non-SIM network should be unchanged
4432         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
4433                 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
4434         // EAP-SIM network should have identity & anonymous identity reset
4435         WifiConfiguration retrievedSimNetwork =
4436                 mWifiConfigManager.getConfiguredNetwork(simNetwork.networkId);
4437         assertEquals("", retrievedSimNetwork.enterpriseConfig.getAnonymousIdentity());
4438         assertEquals("", retrievedSimNetwork.enterpriseConfig.getIdentity());
4439         // PEAP network should have unchanged identity & anonymous identity
4440         WifiConfiguration retrievedPeapSimNetwork =
4441                 mWifiConfigManager.getConfiguredNetwork(peapSimNetwork.networkId);
4442         assertEquals("identity_peap", retrievedPeapSimNetwork.enterpriseConfig.getIdentity());
4443         assertEquals("anonymous_identity_peap",
4444                 retrievedPeapSimNetwork.enterpriseConfig.getAnonymousIdentity());
4445 
4446         mockSession.finishMocking();
4447     }
4448 
4449     /**
4450      * Verifies that SIM configs are reset on {@link WifiConfigManager#loadFromStore()}.
4451      */
4452     @Test
testLoadFromStoreResetsSimIdentity()4453     public void testLoadFromStoreResetsSimIdentity() {
4454         when(mDataTelephonyManager.getSubscriberId()).thenReturn("3214561234567890");
4455         when(mDataTelephonyManager.getSimState()).thenReturn(TelephonyManager.SIM_STATE_READY);
4456         when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
4457         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
4458 
4459         WifiConfiguration simNetwork = WifiConfigurationTestUtil.createEapNetwork(
4460                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
4461         simNetwork.enterpriseConfig.setIdentity("identity");
4462         simNetwork.enterpriseConfig.setAnonymousIdentity("anonymous_identity");
4463 
4464         WifiConfiguration peapSimNetwork = WifiConfigurationTestUtil.createEapNetwork(
4465                 WifiEnterpriseConfig.Eap.PEAP, WifiEnterpriseConfig.Phase2.NONE);
4466         peapSimNetwork.enterpriseConfig.setIdentity("identity");
4467         peapSimNetwork.enterpriseConfig.setAnonymousIdentity("anonymous_identity");
4468 
4469         // Set up the store data.
4470         List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
4471             {
4472                 add(simNetwork);
4473                 add(peapSimNetwork);
4474             }
4475         };
4476         setupStoreDataForRead(sharedNetworks, new ArrayList<>());
4477 
4478         // read from store now
4479         assertTrue(mWifiConfigManager.loadFromStore());
4480 
4481         // assert that the expected identities are reset
4482         WifiConfiguration retrievedSimNetwork =
4483                 mWifiConfigManager.getConfiguredNetwork(simNetwork.networkId);
4484         assertEquals("", retrievedSimNetwork.enterpriseConfig.getIdentity());
4485         assertEquals("", retrievedSimNetwork.enterpriseConfig.getAnonymousIdentity());
4486 
4487         WifiConfiguration retrievedPeapNetwork =
4488                 mWifiConfigManager.getConfiguredNetwork(peapSimNetwork.networkId);
4489         assertEquals("identity", retrievedPeapNetwork.enterpriseConfig.getIdentity());
4490         assertEquals("anonymous_identity",
4491                 retrievedPeapNetwork.enterpriseConfig.getAnonymousIdentity());
4492     }
4493 
4494     /**
4495      * Verifies the deletion of ephemeral network using
4496      * {@link WifiConfigManager#userTemporarilyDisabledNetwork(String)}.
4497      */
4498     @Test
testUserDisableNetwork()4499     public void testUserDisableNetwork() throws Exception {
4500         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
4501         List<WifiConfiguration> networks = new ArrayList<>();
4502         networks.add(openNetwork);
4503         verifyAddNetworkToWifiConfigManager(openNetwork);
4504         List<WifiConfiguration> retrievedNetworks =
4505                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
4506         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
4507                 networks, retrievedNetworks);
4508 
4509         verifyExpiryOfTimeout(openNetwork);
4510     }
4511 
4512     /**
4513      * Verifies the disconnection of Passpoint network using
4514      * {@link WifiConfigManager#userTemporarilyDisabledNetwork(String)}.
4515      */
4516     @Test
testDisablePasspointNetwork()4517     public void testDisablePasspointNetwork() throws Exception {
4518         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
4519 
4520         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
4521 
4522         List<WifiConfiguration> networks = new ArrayList<>();
4523         networks.add(passpointNetwork);
4524 
4525         List<WifiConfiguration> retrievedNetworks =
4526                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
4527         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
4528                 networks, retrievedNetworks);
4529 
4530         verifyExpiryOfTimeout(passpointNetwork);
4531     }
4532 
4533     /**
4534      * Verifies the disconnection of Passpoint network using
4535      * {@link WifiConfigManager#userTemporarilyDisabledNetwork(String)} and ensures that any user
4536      * choice set over other networks is removed.
4537      */
4538     @Test
testDisablePasspointNetworkRemovesUserChoice()4539     public void testDisablePasspointNetworkRemovesUserChoice() throws Exception {
4540         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
4541         WifiConfiguration savedNetwork = WifiConfigurationTestUtil.createOpenNetwork();
4542 
4543         verifyAddNetworkToWifiConfigManager(savedNetwork);
4544         verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork);
4545 
4546         // Set connect choice of passpoint network over saved network.
4547         assertTrue(
4548                 mWifiConfigManager.setNetworkConnectChoice(
4549                         savedNetwork.networkId, passpointNetwork.getKey()));
4550 
4551         WifiConfiguration retrievedSavedNetwork =
4552                 mWifiConfigManager.getConfiguredNetwork(savedNetwork.networkId);
4553         assertEquals(
4554                 passpointNetwork.getKey(),
4555                 retrievedSavedNetwork.getNetworkSelectionStatus().getConnectChoice());
4556 
4557         // Disable the passpoint network & ensure the user choice is now removed from saved network.
4558         mWifiConfigManager.userTemporarilyDisabledNetwork(passpointNetwork.FQDN, TEST_UPDATE_UID);
4559 
4560         retrievedSavedNetwork = mWifiConfigManager.getConfiguredNetwork(savedNetwork.networkId);
4561         assertNull(retrievedSavedNetwork.getNetworkSelectionStatus().getConnectChoice());
4562     }
4563 
4564     @Test
testUserEnableDisabledNetwork()4565     public void  testUserEnableDisabledNetwork() {
4566         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
4567         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
4568         List<WifiConfiguration> networks = new ArrayList<>();
4569         networks.add(openNetwork);
4570         verifyAddNetworkToWifiConfigManager(openNetwork);
4571         List<WifiConfiguration> retrievedNetworks =
4572                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
4573         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
4574                 networks, retrievedNetworks);
4575 
4576         mWifiConfigManager.userTemporarilyDisabledNetwork(openNetwork.SSID, TEST_UPDATE_UID);
4577         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(openNetwork.SSID));
4578         mWifiConfigManager.userEnabledNetwork(retrievedNetworks.get(0).networkId);
4579         assertFalse(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(openNetwork.SSID));
4580         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_DISCONNECT_WIFI),
4581                 anyInt());
4582     }
4583 
4584     @Test
testUserAddOrUpdateSavedNetworkEnableNetwork()4585     public void testUserAddOrUpdateSavedNetworkEnableNetwork() {
4586         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
4587         List<WifiConfiguration> networks = new ArrayList<>();
4588         networks.add(openNetwork);
4589         mWifiConfigManager.userTemporarilyDisabledNetwork(openNetwork.SSID, TEST_UPDATE_UID);
4590         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(openNetwork.SSID));
4591 
4592         verifyAddNetworkToWifiConfigManager(openNetwork);
4593         List<WifiConfiguration> retrievedNetworks =
4594                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
4595         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
4596                 networks, retrievedNetworks);
4597         assertFalse(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(openNetwork.SSID));
4598     }
4599 
4600     @Test
testUserAddPasspointNetworkEnableNetwork()4601     public void testUserAddPasspointNetworkEnableNetwork() {
4602         WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
4603         List<WifiConfiguration> networks = new ArrayList<>();
4604         networks.add(passpointNetwork);
4605         mWifiConfigManager.userTemporarilyDisabledNetwork(passpointNetwork.FQDN, TEST_UPDATE_UID);
4606         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(passpointNetwork.FQDN));
4607         // Add new passpoint network will enable the network.
4608         NetworkUpdateResult result = addNetworkToWifiConfigManager(passpointNetwork);
4609         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4610         assertTrue(result.isNewNetwork());
4611 
4612         List<WifiConfiguration> retrievedNetworks =
4613                 mWifiConfigManager.getConfiguredNetworksWithPasswords();
4614         WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
4615                 networks, retrievedNetworks);
4616         assertFalse(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(passpointNetwork.FQDN));
4617 
4618         mWifiConfigManager.userTemporarilyDisabledNetwork(passpointNetwork.FQDN, TEST_UPDATE_UID);
4619         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(passpointNetwork.FQDN));
4620         // Update a existing passpoint network will not enable network.
4621         result = addNetworkToWifiConfigManager(passpointNetwork);
4622         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4623         assertFalse(result.isNewNetwork());
4624         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(passpointNetwork.FQDN));
4625     }
4626 
verifyExpiryOfTimeout(WifiConfiguration config)4627     private void verifyExpiryOfTimeout(WifiConfiguration config) {
4628         // Disable the ephemeral network.
4629         long disableTimeMs = 546643L;
4630         long currentTimeMs = disableTimeMs;
4631         when(mClock.getWallClockMillis()).thenReturn(currentTimeMs);
4632         String network = config.isPasspoint() ? config.FQDN : config.SSID;
4633         mWifiConfigManager.userTemporarilyDisabledNetwork(network, TEST_UPDATE_UID);
4634         // Before timer is triggered, timer will not expiry will enable network.
4635         currentTimeMs = disableTimeMs
4636                 + WifiConfigManager.USER_DISCONNECT_NETWORK_BLOCK_EXPIRY_MS + 1;
4637         when(mClock.getWallClockMillis()).thenReturn(currentTimeMs);
4638         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(network));
4639         for (int i = 0; i < WifiConfigManager.SCAN_RESULT_MISSING_COUNT_THRESHOLD; i++) {
4640             mWifiConfigManager.updateUserDisabledList(new ArrayList<>());
4641         }
4642         // Before the expiry of timeout.
4643         currentTimeMs = currentTimeMs
4644                 + WifiConfigManager.USER_DISCONNECT_NETWORK_BLOCK_EXPIRY_MS - 1;
4645         when(mClock.getWallClockMillis()).thenReturn(currentTimeMs);
4646         assertTrue(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(network));
4647 
4648         // After the expiry of timeout.
4649         currentTimeMs = currentTimeMs
4650                 + WifiConfigManager.USER_DISCONNECT_NETWORK_BLOCK_EXPIRY_MS + 1;
4651         when(mClock.getWallClockMillis()).thenReturn(currentTimeMs);
4652         assertFalse(mWifiConfigManager.isNetworkTemporarilyDisabledByUser(network));
4653     }
4654 
verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( boolean withNetworkSettings, boolean withProfileOwnerPolicy, boolean withDeviceOwnerPolicy, IpConfiguration ipConfiguration, boolean assertSuccess, int networkId)4655     private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4656             boolean withNetworkSettings,
4657             boolean withProfileOwnerPolicy,
4658             boolean withDeviceOwnerPolicy,
4659             IpConfiguration ipConfiguration,
4660             boolean assertSuccess,
4661             int networkId) {
4662         return verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(withNetworkSettings,
4663                 false, false, withProfileOwnerPolicy, withDeviceOwnerPolicy, ipConfiguration,
4664                 assertSuccess, networkId);
4665     }
4666 
verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( boolean withNetworkSettings, boolean withNetworkSetupWizard, boolean withNetworkManagedProvisioning, boolean withProfileOwnerPolicy, boolean withDeviceOwnerPolicy, IpConfiguration ipConfiguration, boolean assertSuccess, int networkId)4667     private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions(
4668             boolean withNetworkSettings,
4669             boolean withNetworkSetupWizard,
4670             boolean withNetworkManagedProvisioning,
4671             boolean withProfileOwnerPolicy,
4672             boolean withDeviceOwnerPolicy,
4673             IpConfiguration ipConfiguration,
4674             boolean assertSuccess,
4675             int networkId) {
4676         WifiConfiguration network;
4677         if (networkId == WifiConfiguration.INVALID_NETWORK_ID) {
4678             network = WifiConfigurationTestUtil.createOpenHiddenNetwork();
4679         } else {
4680             network = mWifiConfigManager.getConfiguredNetwork(networkId);
4681         }
4682         network.setIpConfiguration(ipConfiguration);
4683         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), any()))
4684                 .thenReturn(withDeviceOwnerPolicy);
4685         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), any()))
4686                 .thenReturn(withProfileOwnerPolicy);
4687         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt()))
4688                 .thenReturn(withNetworkSettings);
4689         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt()))
4690                 .thenReturn(withNetworkSetupWizard);
4691         when(mWifiPermissionsUtil.checkNetworkManagedProvisioningPermission(anyInt()))
4692                 .thenReturn(withNetworkManagedProvisioning);
4693         int uid = withNetworkSettings || withNetworkSetupWizard || withNetworkManagedProvisioning
4694                 ? TEST_CREATOR_UID
4695                 : TEST_NO_PERM_UID;
4696         NetworkUpdateResult result = addNetworkToWifiConfigManager(network, uid);
4697         assertEquals(assertSuccess, result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
4698         return result;
4699     }
4700 
createWifiConfigManager()4701     private void createWifiConfigManager() {
4702         mWifiConfigManager =
4703                 new WifiConfigManager(
4704                         mContext, mClock, mUserManager, mWifiCarrierInfoManager,
4705                         mWifiKeyStore, mWifiConfigStore,
4706                         mWifiPermissionsUtil, mWifiPermissionsWrapper, mWifiInjector,
4707                         mNetworkListSharedStoreData, mNetworkListUserStoreData,
4708                         mRandomizedMacStoreData,
4709                         mFrameworkFacade, new Handler(mLooper.getLooper()), mDeviceConfigFacade,
4710                         mWifiScoreCard, mLruConnectionTracker);
4711         mWifiConfigManager.enableVerboseLogging(1);
4712     }
4713 
4714     /**
4715      * This method sets defaults in the provided WifiConfiguration object if not set
4716      * so that it can be used for comparison with the configuration retrieved from
4717      * WifiConfigManager.
4718      */
setDefaults(WifiConfiguration configuration)4719     private void setDefaults(WifiConfiguration configuration) {
4720         if (configuration.allowedProtocols.isEmpty()) {
4721             configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
4722             configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
4723         }
4724         if (configuration.allowedKeyManagement.isEmpty()) {
4725             configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
4726             configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
4727         }
4728         if (configuration.allowedPairwiseCiphers.isEmpty()) {
4729             configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
4730             configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
4731             configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
4732         }
4733         if (configuration.allowedGroupCiphers.isEmpty()) {
4734             configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
4735             configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
4736             configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
4737             configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
4738             configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
4739         }
4740         if (configuration.allowedGroupManagementCiphers.isEmpty()) {
4741             configuration.allowedGroupManagementCiphers
4742                     .set(WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
4743         }
4744         if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) {
4745             configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
4746         }
4747         if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) {
4748             configuration.setProxySettings(IpConfiguration.ProxySettings.NONE);
4749         }
4750         configuration.status = WifiConfiguration.Status.DISABLED;
4751         configuration.getNetworkSelectionStatus().setNetworkSelectionStatus(
4752                 NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED);
4753         configuration.getNetworkSelectionStatus().setNetworkSelectionDisableReason(
4754                 NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER);
4755     }
4756 
4757     /**
4758      * Modifies the provided configuration with creator uid and package name.
4759      */
setCreationDebugParams(WifiConfiguration configuration, int uid, String packageName)4760     private void setCreationDebugParams(WifiConfiguration configuration, int uid,
4761                                         String packageName) {
4762         configuration.creatorUid = configuration.lastUpdateUid = uid;
4763         configuration.creatorName = configuration.lastUpdateName = packageName;
4764     }
4765 
4766     /**
4767      * Modifies the provided configuration with update uid and package name.
4768      */
setUpdateDebugParams(WifiConfiguration configuration)4769     private void setUpdateDebugParams(WifiConfiguration configuration) {
4770         configuration.lastUpdateUid = TEST_UPDATE_UID;
4771         configuration.lastUpdateName = TEST_UPDATE_NAME;
4772     }
4773 
4774     /**
4775      * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that
4776      * the existing |BSSID| field is not the same value as the one being set
4777      */
assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid)4778     private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) {
4779         assertNotEquals(bssid, configuration.BSSID);
4780         configuration.BSSID = bssid;
4781     }
4782 
4783     /**
4784      * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also,
4785      * asserts that the existing |mIpConfiguration| field is not the same value as the one being set
4786      */
assertAndSetNetworkIpConfiguration( WifiConfiguration configuration, IpConfiguration ipConfiguration)4787     private void assertAndSetNetworkIpConfiguration(
4788             WifiConfiguration configuration, IpConfiguration ipConfiguration) {
4789         assertNotEquals(ipConfiguration, configuration.getIpConfiguration());
4790         configuration.setIpConfiguration(ipConfiguration);
4791     }
4792 
4793     /**
4794      * Modifies the provided WifiConfiguration with the specified |wepKeys| value and
4795      * |wepTxKeyIndex|.
4796      */
assertAndSetNetworkWepKeysAndTxIndex( WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx)4797     private void assertAndSetNetworkWepKeysAndTxIndex(
4798             WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) {
4799         assertNotEquals(wepKeys, configuration.wepKeys);
4800         assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex);
4801         configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length);
4802         configuration.wepTxKeyIndex = wepTxKeyIdx;
4803     }
4804 
4805     /**
4806      * Modifies the provided WifiConfiguration with the specified |preSharedKey| value.
4807      */
assertAndSetNetworkPreSharedKey( WifiConfiguration configuration, String preSharedKey)4808     private void assertAndSetNetworkPreSharedKey(
4809             WifiConfiguration configuration, String preSharedKey) {
4810         assertNotEquals(preSharedKey, configuration.preSharedKey);
4811         configuration.preSharedKey = preSharedKey;
4812     }
4813 
4814     /**
4815      * Modifies the provided WifiConfiguration with the specified enteprise |password| value.
4816      */
assertAndSetNetworkEnterprisePassword( WifiConfiguration configuration, String password)4817     private void assertAndSetNetworkEnterprisePassword(
4818             WifiConfiguration configuration, String password) {
4819         assertNotEquals(password, configuration.enterpriseConfig.getPassword());
4820         configuration.enterpriseConfig.setPassword(password);
4821     }
4822 
4823     /**
4824      * Helper method to capture the networks list store data that will be written by
4825      * WifiConfigStore.write() method.
4826      */
4827     private Pair<List<WifiConfiguration>, List<WifiConfiguration>>
captureWriteNetworksListStoreData()4828             captureWriteNetworksListStoreData() {
4829         try {
4830             ArgumentCaptor<ArrayList> sharedConfigsCaptor =
4831                     ArgumentCaptor.forClass(ArrayList.class);
4832             ArgumentCaptor<ArrayList> userConfigsCaptor =
4833                     ArgumentCaptor.forClass(ArrayList.class);
4834             mNetworkListStoreDataMockOrder.verify(mNetworkListSharedStoreData)
4835                     .setConfigurations(sharedConfigsCaptor.capture());
4836             mNetworkListStoreDataMockOrder.verify(mNetworkListUserStoreData)
4837                     .setConfigurations(userConfigsCaptor.capture());
4838             mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean());
4839             return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue());
4840         } catch (Exception e) {
4841             fail("Exception encountered during write " + e);
4842         }
4843         return null;
4844     }
4845 
4846     /**
4847      * Returns whether the provided network was in the store data or not.
4848      */
isNetworkInConfigStoreData(WifiConfiguration configuration)4849     private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) {
4850         Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData =
4851                 captureWriteNetworksListStoreData();
4852         if (networkListStoreData == null) {
4853             return false;
4854         }
4855         List<WifiConfiguration> networkList = new ArrayList<>();
4856         networkList.addAll(networkListStoreData.first);
4857         networkList.addAll(networkListStoreData.second);
4858         return isNetworkInConfigStoreData(configuration, networkList);
4859     }
4860 
4861     /**
4862      * Returns whether the provided network was in the store data or not.
4863      */
isNetworkInConfigStoreData( WifiConfiguration configuration, List<WifiConfiguration> networkList)4864     private boolean isNetworkInConfigStoreData(
4865             WifiConfiguration configuration, List<WifiConfiguration> networkList) {
4866         boolean foundNetworkInStoreData = false;
4867         for (WifiConfiguration retrievedConfig : networkList) {
4868             if (retrievedConfig.getKey().equals(configuration.getKey())) {
4869                 foundNetworkInStoreData = true;
4870                 break;
4871             }
4872         }
4873         return foundNetworkInStoreData;
4874     }
4875 
4876     /**
4877      * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData
4878      * after WifiConfigStore#read.
4879      */
setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations, List<WifiConfiguration> userConfigurations)4880     private void setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations,
4881             List<WifiConfiguration> userConfigurations) {
4882         when(mNetworkListSharedStoreData.getConfigurations())
4883                 .thenReturn(sharedConfigurations);
4884         when(mNetworkListUserStoreData.getConfigurations()).thenReturn(userConfigurations);
4885     }
4886 
4887     /**
4888      * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData
4889      * after WifiConfigStore#switchUserStoresAndRead.
4890      */
setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations, Map<String, Long> deletedEphemeralSsids)4891     private void setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations,
4892             Map<String, Long> deletedEphemeralSsids) {
4893         when(mNetworkListUserStoreData.getConfigurations()).thenReturn(userConfigurations);
4894     }
4895 
4896     /**
4897      * Verifies that the provided network was not present in the last config store write.
4898      */
verifyNetworkNotInConfigStoreData(WifiConfiguration configuration)4899     private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) {
4900         assertFalse(isNetworkInConfigStoreData(configuration));
4901     }
4902 
4903     /**
4904      * Verifies that the provided network was present in the last config store write.
4905      */
verifyNetworkInConfigStoreData(WifiConfiguration configuration)4906     private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) {
4907         assertTrue(isNetworkInConfigStoreData(configuration));
4908     }
4909 
assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration)4910     private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) {
4911         if (!TextUtils.isEmpty(configuration.preSharedKey)) {
4912             assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey);
4913         }
4914         if (configuration.wepKeys != null) {
4915             for (int i = 0; i < configuration.wepKeys.length; i++) {
4916                 if (!TextUtils.isEmpty(configuration.wepKeys[i])) {
4917                     assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]);
4918                 }
4919             }
4920         }
4921         if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) {
4922             assertEquals(
4923                     WifiConfigManager.PASSWORD_MASK,
4924                     configuration.enterpriseConfig.getPassword());
4925         }
4926     }
4927 
assertRandomizedMacAddressMaskedInWifiConfiguration( WifiConfiguration configuration)4928     private void assertRandomizedMacAddressMaskedInWifiConfiguration(
4929             WifiConfiguration configuration) {
4930         MacAddress defaultMac = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
4931         MacAddress randomizedMacAddress = configuration.getRandomizedMacAddress();
4932         if (randomizedMacAddress != null) {
4933             assertEquals(defaultMac, randomizedMacAddress);
4934         }
4935     }
4936 
4937     /**
4938      * Verifies that the network was present in the network change broadcast and returns the
4939      * change reason.
4940      */
verifyNetworkInBroadcastAndReturnReason()4941     private int verifyNetworkInBroadcastAndReturnReason() {
4942         ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
4943         mContextConfigStoreMockOrder.verify(mContext).sendBroadcastAsUser(
4944                 intentCaptor.capture(),
4945                 eq(UserHandle.ALL),
4946                 eq(android.Manifest.permission.ACCESS_WIFI_STATE));
4947 
4948         Intent intent = intentCaptor.getValue();
4949 
4950         WifiConfiguration retrievedConfig =
4951                 (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION);
4952         assertNull(retrievedConfig);
4953 
4954         return intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1);
4955     }
4956 
4957     /**
4958      * Verifies that we sent out an add broadcast with the provided network.
4959      */
verifyNetworkAddBroadcast()4960     private void verifyNetworkAddBroadcast() {
4961         assertEquals(
4962                 verifyNetworkInBroadcastAndReturnReason(),
4963                 WifiManager.CHANGE_REASON_ADDED);
4964     }
4965 
4966     /**
4967      * Verifies that we sent out an update broadcast with the provided network.
4968      */
verifyNetworkUpdateBroadcast()4969     private void verifyNetworkUpdateBroadcast() {
4970         assertEquals(
4971                 verifyNetworkInBroadcastAndReturnReason(),
4972                 WifiManager.CHANGE_REASON_CONFIG_CHANGE);
4973     }
4974 
4975     /**
4976      * Verifies that we sent out a remove broadcast with the provided network.
4977      */
verifyNetworkRemoveBroadcast()4978     private void verifyNetworkRemoveBroadcast() {
4979         assertEquals(
4980                 verifyNetworkInBroadcastAndReturnReason(),
4981                 WifiManager.CHANGE_REASON_REMOVED);
4982     }
4983 
verifyWifiConfigStoreRead()4984     private void verifyWifiConfigStoreRead() {
4985         assertTrue(mWifiConfigManager.loadFromStore());
4986         mContextConfigStoreMockOrder.verify(mContext).sendBroadcastAsUser(
4987                 any(Intent.class),
4988                 any(UserHandle.class),
4989                 eq(android.Manifest.permission.ACCESS_WIFI_STATE));
4990     }
4991 
triggerStoreReadIfNeeded()4992     private void triggerStoreReadIfNeeded() {
4993         // Trigger a store read if not already done.
4994         if (!mStoreReadTriggered) {
4995             verifyWifiConfigStoreRead();
4996             mStoreReadTriggered = true;
4997         }
4998     }
4999 
5000     /**
5001      * Adds the provided configuration to WifiConfigManager with uid = TEST_CREATOR_UID.
5002      */
addNetworkToWifiConfigManager(WifiConfiguration configuration)5003     private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) {
5004         return addNetworkToWifiConfigManager(configuration, TEST_CREATOR_UID, null);
5005     }
5006 
5007     /**
5008      * Adds the provided configuration to WifiConfigManager with uid specified.
5009      */
addNetworkToWifiConfigManager(WifiConfiguration configuration, int uid)5010     private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration,
5011                                                               int uid) {
5012         return addNetworkToWifiConfigManager(configuration, uid, null);
5013     }
5014 
5015     /**
5016      * Adds the provided configuration to WifiConfigManager and modifies the provided configuration
5017      * with creator/update uid, package name and time. This also sets defaults for fields not
5018      * populated.
5019      * These fields are populated internally by WifiConfigManager and hence we need
5020      * to modify the configuration before we compare the added network with the retrieved network.
5021      * This method also triggers a store read if not already done.
5022      */
addNetworkToWifiConfigManager(WifiConfiguration configuration, int uid, @Nullable String packageName)5023     private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration,
5024                                                               int uid,
5025                                                               @Nullable String packageName) {
5026         clearInvocations(mContext, mWifiConfigStore, mNetworkListSharedStoreData,
5027                 mNetworkListUserStoreData);
5028         triggerStoreReadIfNeeded();
5029         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS);
5030         NetworkUpdateResult result =
5031                 mWifiConfigManager.addOrUpdateNetwork(configuration, uid, packageName);
5032         setDefaults(configuration);
5033         setCreationDebugParams(
5034                 configuration, uid, packageName != null ? packageName : TEST_CREATOR_NAME);
5035         configuration.networkId = result.getNetworkId();
5036         return result;
5037     }
5038 
5039     /**
5040      * Add network to WifiConfigManager and ensure that it was successful.
5041      */
verifyAddNetworkToWifiConfigManager( WifiConfiguration configuration)5042     private NetworkUpdateResult verifyAddNetworkToWifiConfigManager(
5043             WifiConfiguration configuration) {
5044         NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
5045         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
5046         assertTrue(result.isNewNetwork());
5047         assertTrue(result.hasIpChanged());
5048         assertTrue(result.hasProxyChanged());
5049 
5050         verifyNetworkAddBroadcast();
5051         // Verify that the config store write was triggered with this new configuration.
5052         verifyNetworkInConfigStoreData(configuration);
5053         return result;
5054     }
5055 
5056     /**
5057      * Add ephemeral network to WifiConfigManager and ensure that it was successful.
5058      */
verifyAddEphemeralNetworkToWifiConfigManager( WifiConfiguration configuration)5059     private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager(
5060             WifiConfiguration configuration) throws Exception {
5061         NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
5062         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
5063         assertTrue(result.isNewNetwork());
5064         assertTrue(result.hasIpChanged());
5065         assertTrue(result.hasProxyChanged());
5066 
5067         verifyNetworkAddBroadcast();
5068         // Ensure that the write was not invoked for ephemeral network addition.
5069         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
5070         return result;
5071     }
5072 
5073     /**
5074      * Add ephemeral network to WifiConfigManager and ensure that it was successful.
5075      */
verifyAddSuggestionOrRequestNetworkToWifiConfigManager( WifiConfiguration configuration)5076     private NetworkUpdateResult verifyAddSuggestionOrRequestNetworkToWifiConfigManager(
5077             WifiConfiguration configuration) throws Exception {
5078         NetworkUpdateResult result =
5079                 addNetworkToWifiConfigManager(configuration, TEST_CREATOR_UID, TEST_CREATOR_NAME);
5080         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
5081         assertTrue(result.isNewNetwork());
5082         assertTrue(result.hasIpChanged());
5083         assertTrue(result.hasProxyChanged());
5084 
5085         verifyNetworkAddBroadcast();
5086         // Ensure that the write was not invoked for ephemeral network addition.
5087         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
5088         return result;
5089     }
5090 
5091     /**
5092      * Add Passpoint network to WifiConfigManager and ensure that it was successful.
5093      */
verifyAddPasspointNetworkToWifiConfigManager( WifiConfiguration configuration)5094     private NetworkUpdateResult verifyAddPasspointNetworkToWifiConfigManager(
5095             WifiConfiguration configuration) throws Exception {
5096         NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
5097         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
5098         assertTrue(result.isNewNetwork());
5099         assertTrue(result.hasIpChanged());
5100         assertTrue(result.hasProxyChanged());
5101 
5102         // Verify keys are not being installed.
5103         verify(mWifiKeyStore, never()).updateNetworkKeys(any(WifiConfiguration.class),
5104                 any(WifiConfiguration.class));
5105         verifyNetworkAddBroadcast();
5106         // Ensure that the write was not invoked for Passpoint network addition.
5107         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
5108         return result;
5109     }
5110 
5111     /**
5112      * Updates the provided configuration to WifiConfigManager and modifies the provided
5113      * configuration with update uid, package name and time.
5114      * These fields are populated internally by WifiConfigManager and hence we need
5115      * to modify the configuration before we compare the added network with the retrieved network.
5116      */
updateNetworkToWifiConfigManager(WifiConfiguration configuration)5117     private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) {
5118         clearInvocations(mContext, mWifiConfigStore, mNetworkListSharedStoreData,
5119                 mNetworkListUserStoreData);
5120         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
5121         NetworkUpdateResult result =
5122                 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID);
5123         setUpdateDebugParams(configuration);
5124         return result;
5125     }
5126 
5127     /**
5128      * Update network to WifiConfigManager config change and ensure that it was successful.
5129      */
verifyUpdateNetworkToWifiConfigManager( WifiConfiguration configuration)5130     private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager(
5131             WifiConfiguration configuration) {
5132         NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration);
5133         assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
5134         assertFalse(result.isNewNetwork());
5135 
5136         verifyNetworkUpdateBroadcast();
5137         // Verify that the config store write was triggered with this new configuration.
5138         verifyNetworkInConfigStoreData(configuration);
5139         return result;
5140     }
5141 
5142     /**
5143      * Update network to WifiConfigManager without IP config change and ensure that it was
5144      * successful.
5145      */
verifyUpdateNetworkToWifiConfigManagerWithoutIpChange( WifiConfiguration configuration)5146     private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(
5147             WifiConfiguration configuration) {
5148         NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
5149         assertFalse(result.hasIpChanged());
5150         assertFalse(result.hasProxyChanged());
5151         return result;
5152     }
5153 
5154     /**
5155      * Update network to WifiConfigManager with IP config change and ensure that it was
5156      * successful.
5157      */
verifyUpdateNetworkToWifiConfigManagerWithIpChange( WifiConfiguration configuration)5158     private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange(
5159             WifiConfiguration configuration) {
5160         NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
5161         assertTrue(result.hasIpChanged());
5162         assertTrue(result.hasProxyChanged());
5163         return result;
5164     }
5165 
5166     /**
5167      * Removes network from WifiConfigManager and ensure that it was successful.
5168      */
verifyRemoveNetworkFromWifiConfigManager( WifiConfiguration configuration)5169     private void verifyRemoveNetworkFromWifiConfigManager(
5170             WifiConfiguration configuration) {
5171         assertTrue(mWifiConfigManager.removeNetwork(
5172                 configuration.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
5173 
5174         verifyNetworkRemoveBroadcast();
5175         // Verify if the config store write was triggered without this new configuration.
5176         verifyNetworkNotInConfigStoreData(configuration);
5177         verify(mBssidBlocklistMonitor, atLeastOnce()).handleNetworkRemoved(configuration.SSID);
5178     }
5179 
5180     /**
5181      * Removes ephemeral network from WifiConfigManager and ensure that it was successful.
5182      */
verifyRemoveEphemeralNetworkFromWifiConfigManager( WifiConfiguration configuration)5183     private void verifyRemoveEphemeralNetworkFromWifiConfigManager(
5184             WifiConfiguration configuration) throws Exception {
5185         assertTrue(mWifiConfigManager.removeNetwork(
5186                 configuration.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
5187 
5188         verifyNetworkRemoveBroadcast();
5189         // Ensure that the write was not invoked for ephemeral network remove.
5190         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
5191     }
5192 
5193     /**
5194      * Removes Passpoint network from WifiConfigManager and ensure that it was successful.
5195      */
verifyRemovePasspointNetworkFromWifiConfigManager( WifiConfiguration configuration)5196     private void verifyRemovePasspointNetworkFromWifiConfigManager(
5197             WifiConfiguration configuration) throws Exception {
5198         assertTrue(mWifiConfigManager.removeNetwork(
5199                 configuration.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME));
5200 
5201         // Verify keys are not being removed.
5202         verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class));
5203         verifyNetworkRemoveBroadcast();
5204         // Ensure that the write was not invoked for Passpoint network remove.
5205         mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
5206     }
5207 
5208     /**
5209      * Verifies the provided network's public status and ensures that the network change broadcast
5210      * has been sent out.
5211      */
verifyUpdateNetworkStatus(WifiConfiguration configuration, int status)5212     private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) {
5213         assertEquals(status, configuration.status);
5214         verifyNetworkUpdateBroadcast();
5215     }
5216 
5217     /**
5218      * Verifies the network's selection status update.
5219      *
5220      * For temporarily disabled reasons, the method ensures that the status has changed only if
5221      * disable reason counter has exceeded the threshold.
5222      *
5223      * For permanently disabled/enabled reasons, the method ensures that the public status has
5224      * changed and the network change broadcast has been sent out.
5225      */
verifyUpdateNetworkSelectionStatus( int networkId, int reason, int temporaryDisableReasonCounter)5226     private void verifyUpdateNetworkSelectionStatus(
5227             int networkId, int reason, int temporaryDisableReasonCounter) {
5228         when(mClock.getElapsedSinceBootMillis())
5229                 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS);
5230 
5231         // Fetch the current status of the network before we try to update the status.
5232         WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
5233         NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus();
5234         int currentDisableReason = currentStatus.getNetworkSelectionDisableReason();
5235 
5236         // First set the status to the provided reason.
5237         assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason));
5238 
5239         // Now fetch the network configuration and verify the new status of the network.
5240         retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
5241 
5242         NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
5243         int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason();
5244         long retrievedDisableTime = retrievedStatus.getDisableTime();
5245         int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason);
5246         int disableReasonThreshold =
5247                 WifiConfigManager.getNetworkSelectionDisableThreshold(reason);
5248 
5249         if (reason == NetworkSelectionStatus.DISABLED_NONE) {
5250             assertEquals(reason, retrievedDisableReason);
5251             assertTrue(retrievedStatus.isNetworkEnabled());
5252             assertEquals(
5253                     NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
5254                     retrievedDisableTime);
5255             verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
5256         } else if (reason < NetworkSelectionStatus.PERMANENTLY_DISABLED_STARTING_INDEX) {
5257             // For temporarily disabled networks, we need to ensure that the current status remains
5258             // until the threshold is crossed.
5259             assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter);
5260             if (retrievedDisableReasonCounter < disableReasonThreshold) {
5261                 assertEquals(currentDisableReason, retrievedDisableReason);
5262                 assertEquals(
5263                         currentStatus.getNetworkSelectionStatus(),
5264                         retrievedStatus.getNetworkSelectionStatus());
5265             } else {
5266                 assertEquals(reason, retrievedDisableReason);
5267                 assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
5268                 assertEquals(
5269                         TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime);
5270             }
5271         } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) {
5272             assertEquals(reason, retrievedDisableReason);
5273             assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
5274             assertEquals(
5275                     NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
5276                     retrievedDisableTime);
5277             verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
5278         }
5279     }
5280 
5281     /**
5282      * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency
5283      * values.
5284      */
createScanDetailForNetwork( WifiConfiguration configuration, String bssid, int level, int frequency)5285     private ScanDetail createScanDetailForNetwork(
5286             WifiConfiguration configuration, String bssid, int level, int frequency) {
5287         return WifiConfigurationTestUtil.createScanDetailForNetwork(configuration, bssid, level,
5288                 frequency, mClock.getUptimeSinceBootMillis(), mClock.getWallClockMillis());
5289     }
5290     /**
5291      * Creates a scan detail corresponding to the provided network and BSSID value.
5292      */
createScanDetailForNetwork(WifiConfiguration configuration, String bssid)5293     private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) {
5294         return createScanDetailForNetwork(configuration, bssid, 0, 0);
5295     }
5296 
5297     /**
5298      * Creates a scan detail corresponding to the provided network and fixed BSSID value.
5299      */
createScanDetailForNetwork(WifiConfiguration configuration)5300     private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) {
5301         return createScanDetailForNetwork(configuration, TEST_BSSID);
5302     }
5303 
5304     /**
5305      * Adds the provided network and then creates a scan detail corresponding to the network. The
5306      * method then creates a ScanDetail corresponding to the network and ensures that the network
5307      * is properly matched using
5308      * {@link WifiConfigManager#getConfiguredNetworkForScanDetailAndCache(ScanDetail)} and also
5309      * verifies that the provided scan detail was cached,
5310      */
verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( WifiConfiguration network)5311     private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
5312             WifiConfiguration network) {
5313         // First add the provided network.
5314         verifyAddNetworkToWifiConfigManager(network);
5315 
5316         // Now create a dummy scan detail corresponding to the network.
5317         ScanDetail scanDetail = createScanDetailForNetwork(network);
5318         ScanResult scanResult = scanDetail.getScanResult();
5319 
5320         WifiConfiguration retrievedNetwork =
5321                 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(scanDetail);
5322         // Retrieve the network with password data for comparison.
5323         retrievedNetwork =
5324                 mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId);
5325 
5326         WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
5327                 network, retrievedNetwork);
5328 
5329         // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
5330         ScanDetailCache retrievedScanDetailCache =
5331                 mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId);
5332         assertEquals(1, retrievedScanDetailCache.size());
5333         ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID);
5334 
5335         ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
5336     }
5337 
5338     /**
5339      * Adds a new network and verifies that the |HasEverConnected| flag is set to false.
5340      */
verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network)5341     private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) {
5342         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
5343         WifiConfiguration retrievedNetwork =
5344                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
5345         assertFalse("Adding a new network should not have hasEverConnected set to true.",
5346                 retrievedNetwork.getNetworkSelectionStatus().hasEverConnected());
5347     }
5348 
5349     /**
5350      * Updates an existing network with some credential change and verifies that the
5351      * |HasEverConnected| flag is set to false.
5352      */
verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse( WifiConfiguration network)5353     private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(
5354             WifiConfiguration network) {
5355         NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
5356         WifiConfiguration retrievedNetwork =
5357                 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
5358         assertFalse("Updating network credentials config should clear hasEverConnected.",
5359                 retrievedNetwork.getNetworkSelectionStatus().hasEverConnected());
5360         assertTrue(result.hasCredentialChanged());
5361     }
5362 
5363     /**
5364      * Updates an existing network after connection using
5365      * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the
5366      * |HasEverConnected| flag is set to true.
5367      */
verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId)5368     private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) {
5369         assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId));
5370         WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
5371         assertTrue("hasEverConnected expected to be true after connection.",
5372                 retrievedNetwork.getNetworkSelectionStatus().hasEverConnected());
5373         assertEquals(0, mLruConnectionTracker.getAgeIndexOfNetwork(retrievedNetwork));
5374     }
5375 
5376     /**
5377      * Sets up a user profiles for WifiConfigManager testing.
5378      *
5379      * @param userId Id of the user.
5380      */
setupUserProfiles(int userId)5381     private void setupUserProfiles(int userId) {
5382         when(mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(userId))).thenReturn(true);
5383     }
5384 
verifyRemoveNetworksForApp()5385     private void verifyRemoveNetworksForApp() {
5386         verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
5387         verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
5388         verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
5389 
5390         assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
5391 
5392         ApplicationInfo app = new ApplicationInfo();
5393         app.uid = TEST_CREATOR_UID;
5394         app.packageName = TEST_CREATOR_NAME;
5395         assertEquals(3, mWifiConfigManager.removeNetworksForApp(app).size());
5396 
5397         // Ensure all the networks are removed now.
5398         assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
5399     }
5400 
5401     /**
5402      * Verifies SSID blacklist consistent with Watchdog trigger.
5403      *
5404      * Expected behavior: A SSID won't gets blacklisted if there only signle SSID
5405      * be observed and Watchdog trigger is activated.
5406      */
5407     @Test
verifyConsistentWatchdogAndSsidBlacklist()5408     public void verifyConsistentWatchdogAndSsidBlacklist() {
5409 
5410         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
5411         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
5412 
5413         when(mWifiInjector.getWifiLastResortWatchdog().shouldIgnoreSsidUpdate())
5414                 .thenReturn(true);
5415 
5416         int networkId = result.getNetworkId();
5417         // First set it to enabled.
5418         verifyUpdateNetworkSelectionStatus(
5419                 networkId, NetworkSelectionStatus.DISABLED_NONE, 0);
5420 
5421         int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
5422         int assocRejectThreshold =
5423                 WifiConfigManager.getNetworkSelectionDisableThreshold(assocRejectReason);
5424         for (int i = 1; i <= assocRejectThreshold; i++) {
5425             assertFalse(mWifiConfigManager.updateNetworkSelectionStatus(
5426                         networkId, assocRejectReason));
5427         }
5428 
5429         assertFalse(mWifiConfigManager.getConfiguredNetwork(networkId)
5430                     .getNetworkSelectionStatus().isNetworkTemporaryDisabled());
5431     }
5432 
5433     /**
5434      * Verifies that isInFlakyRandomizationSsidHotlist returns true if the network's SSID is in
5435      * the hotlist and the network is using randomized MAC.
5436      */
5437     @Test
testFlakyRandomizationSsidHotlist()5438     public void testFlakyRandomizationSsidHotlist() {
5439         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
5440         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
5441         int networkId = result.getNetworkId();
5442 
5443         // should return false when there is nothing in the hotlist
5444         assertFalse(mWifiConfigManager.isInFlakyRandomizationSsidHotlist(networkId));
5445 
5446         // add the network's SSID to the hotlist and verify the method returns true
5447         Set<String> ssidHotlist = new HashSet<>();
5448         ssidHotlist.add(openNetwork.SSID);
5449         when(mDeviceConfigFacade.getRandomizationFlakySsidHotlist()).thenReturn(ssidHotlist);
5450         assertTrue(mWifiConfigManager.isInFlakyRandomizationSsidHotlist(networkId));
5451 
5452         // Now change the macRandomizationSetting to "trusted" and then verify
5453         // isInFlakyRandomizationSsidHotlist returns false
5454         openNetwork.macRandomizationSetting = WifiConfiguration.RANDOMIZATION_NONE;
5455         NetworkUpdateResult networkUpdateResult = updateNetworkToWifiConfigManager(openNetwork);
5456         assertNotEquals(WifiConfiguration.INVALID_NETWORK_ID, networkUpdateResult.getNetworkId());
5457         assertFalse(mWifiConfigManager.isInFlakyRandomizationSsidHotlist(networkId));
5458     }
5459 
5460     /**
5461      * Verifies that findScanRssi returns valid RSSI when scan was done recently
5462      */
5463     @Test
testFindScanRssiRecentScan()5464     public void testFindScanRssiRecentScan() {
5465         // First add the provided network.
5466         WifiConfiguration testNetwork = WifiConfigurationTestUtil.createOpenNetwork();
5467         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(testNetwork);
5468 
5469         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS);
5470         ScanDetail scanDetail = createScanDetailForNetwork(testNetwork, TEST_BSSID,
5471                 TEST_RSSI, TEST_FREQUENCY_1);
5472         ScanResult scanResult = scanDetail.getScanResult();
5473 
5474         mWifiConfigManager.updateScanDetailCacheFromScanDetail(scanDetail);
5475         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS + 2000);
5476         assertEquals(mWifiConfigManager.findScanRssi(result.getNetworkId(), 5000), TEST_RSSI);
5477     }
5478 
5479     /**
5480      * Verifies that findScanRssi returns INVALID_RSSI when scan was done a long time ago
5481      */
5482     @Test
testFindScanRssiOldScan()5483     public void testFindScanRssiOldScan() {
5484         // First add the provided network.
5485         WifiConfiguration testNetwork = WifiConfigurationTestUtil.createOpenNetwork();
5486         NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(testNetwork);
5487 
5488         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS);
5489         ScanDetail scanDetail = createScanDetailForNetwork(testNetwork, TEST_BSSID,
5490                 TEST_RSSI, TEST_FREQUENCY_1);
5491         ScanResult scanResult = scanDetail.getScanResult();
5492 
5493         mWifiConfigManager.updateScanDetailCacheFromScanDetail(scanDetail);
5494         when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS + 15000);
5495         assertEquals(mWifiConfigManager.findScanRssi(result.getNetworkId(), 5000),
5496                 WifiInfo.INVALID_RSSI);
5497     }
5498 
5499     /**
5500      * Verify when save to store, isMostRecentlyConnected flag will be set.
5501      */
5502     @Test
testMostRecentlyConnectedNetwork()5503     public void testMostRecentlyConnectedNetwork() {
5504         WifiConfiguration testNetwork1 = WifiConfigurationTestUtil.createOpenNetwork();
5505         verifyAddNetworkToWifiConfigManager(testNetwork1);
5506         WifiConfiguration testNetwork2 = WifiConfigurationTestUtil.createOpenNetwork();
5507         verifyAddNetworkToWifiConfigManager(testNetwork2);
5508         mWifiConfigManager.updateNetworkAfterConnect(testNetwork2.networkId);
5509         mWifiConfigManager.saveToStore(true);
5510         Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkStoreData =
5511                 captureWriteNetworksListStoreData();
5512         List<WifiConfiguration> sharedNetwork = networkStoreData.first;
5513         assertFalse(sharedNetwork.get(0).isMostRecentlyConnected);
5514         assertTrue(sharedNetwork.get(1).isMostRecentlyConnected);
5515     }
5516 
5517     /**
5518      * Verify scan comparator gives the most recently connected network highest priority
5519      */
5520     @Test
testScanComparator()5521     public void testScanComparator() {
5522         WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
5523         verifyAddNetworkToWifiConfigManager(network1);
5524         WifiConfiguration network2 = WifiConfigurationTestUtil.createOpenNetwork();
5525         verifyAddNetworkToWifiConfigManager(network2);
5526         WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenNetwork();
5527         verifyAddNetworkToWifiConfigManager(network3);
5528         WifiConfiguration network4 = WifiConfigurationTestUtil.createOpenNetwork();
5529         verifyAddNetworkToWifiConfigManager(network4);
5530 
5531         // Connect two network in order, network3 --> network2
5532         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(network3.networkId);
5533         verifyUpdateNetworkAfterConnectHasEverConnectedTrue(network2.networkId);
5534         // Set network4 {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} to true.
5535         assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(network4.networkId,
5536                 createScanDetailForNetwork(network4).getScanResult(), 54));
5537         List<WifiConfiguration> networkList = mWifiConfigManager.getConfiguredNetworks();
5538         // Expected order should be based on connection order and last qualified selection.
5539         Collections.sort(networkList, mWifiConfigManager.getScanListComparator());
5540         assertEquals(network2.SSID, networkList.get(0).SSID);
5541         assertEquals(network3.SSID, networkList.get(1).SSID);
5542         assertEquals(network4.SSID, networkList.get(2).SSID);
5543         assertEquals(network1.SSID, networkList.get(3).SSID);
5544         // Remove network to check the age index changes.
5545         mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME);
5546         assertEquals(Integer.MAX_VALUE, mLruConnectionTracker.getAgeIndexOfNetwork(network3));
5547         assertEquals(0, mLruConnectionTracker.getAgeIndexOfNetwork(network2));
5548         mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID, TEST_CREATOR_NAME);
5549         assertEquals(Integer.MAX_VALUE, mLruConnectionTracker.getAgeIndexOfNetwork(network2));
5550     }
5551 }
5552