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