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