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