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