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