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