WifiConfigManagerTest.java revision 2f5d10a29d17781e903eeddedb4a547e62c55524
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 that the list of PNO networks does not contain any permanently or temporarily 1523 * disabled networks. 1524 * {@link WifiConfigManager#retrievePnoNetworkList()}. 1525 */ 1526 @Test 1527 public void testRetrievePnoListDoesNotContainDisabledNetworks() throws Exception { 1528 // Create and add 2 networks. 1529 WifiConfiguration network1 = WifiConfigurationTestUtil.createEapNetwork(); 1530 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1531 1532 NetworkUpdateResult result1 = verifyAddNetworkToWifiConfigManager(network1); 1533 NetworkUpdateResult result2 = verifyAddNetworkToWifiConfigManager(network2); 1534 1535 // Enable all of them. 1536 verifyUpdateNetworkSelectionStatus( 1537 result1.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 1538 verifyUpdateNetworkSelectionStatus( 1539 result2.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 1540 1541 // Set network1 to temporarily disabled. The threshold for association rejection is 5, so 1542 // disable it 5 times to actually mark it temporarily disabled. 1543 int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION; 1544 int assocRejectThreshold = 1545 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason]; 1546 for (int i = 1; i <= assocRejectThreshold; i++) { 1547 verifyUpdateNetworkSelectionStatus(result1.getNetworkId(), assocRejectReason, i); 1548 } 1549 1550 // Set network 2 to permanently disabled. 1551 verifyUpdateNetworkSelectionStatus( 1552 result2.getNetworkId(), NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER, 0); 1553 1554 // Retrieve the Pno network list & verify both networks are not included. 1555 List<WifiScanner.PnoSettings.PnoNetwork> pnoNetworks = 1556 mWifiConfigManager.retrievePnoNetworkList(); 1557 assertEquals(0, pnoNetworks.size()); 1558 } 1559 1560 /** 1561 * Verifies the linking of networks when they have the same default GW Mac address in 1562 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1563 */ 1564 @Test 1565 public void testNetworkLinkUsingGwMacAddress() { 1566 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1567 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1568 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1569 verifyAddNetworkToWifiConfigManager(network1); 1570 verifyAddNetworkToWifiConfigManager(network2); 1571 verifyAddNetworkToWifiConfigManager(network3); 1572 1573 // Set the same default GW mac address for all of the networks. 1574 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1575 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1576 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1577 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1578 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1579 network3.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1580 1581 // Now create dummy scan detail corresponding to the networks. 1582 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1); 1583 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2); 1584 ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3); 1585 1586 // Now save all these scan details corresponding to each of this network and expect 1587 // all of these networks to be linked with each other. 1588 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1589 networkScanDetail1)); 1590 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1591 networkScanDetail2)); 1592 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1593 networkScanDetail3)); 1594 1595 List<WifiConfiguration> retrievedNetworks = 1596 mWifiConfigManager.getConfiguredNetworks(); 1597 for (WifiConfiguration network : retrievedNetworks) { 1598 assertEquals(2, network.linkedConfigurations.size()); 1599 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1600 if (otherNetwork == network) { 1601 continue; 1602 } 1603 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1604 } 1605 } 1606 } 1607 1608 /** 1609 * Verifies the linking of networks when they have scan results with same first 16 ASCII of 1610 * bssid in 1611 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1612 */ 1613 @Test 1614 public void testNetworkLinkUsingBSSIDMatch() { 1615 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1616 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1617 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1618 verifyAddNetworkToWifiConfigManager(network1); 1619 verifyAddNetworkToWifiConfigManager(network2); 1620 verifyAddNetworkToWifiConfigManager(network3); 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 ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3, "af:89:56:34:56:69"); 1626 1627 // Now save all these scan details corresponding to each of this network and expect 1628 // all of these networks to be linked with each other. 1629 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1630 networkScanDetail1)); 1631 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1632 networkScanDetail2)); 1633 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1634 networkScanDetail3)); 1635 1636 List<WifiConfiguration> retrievedNetworks = 1637 mWifiConfigManager.getConfiguredNetworks(); 1638 for (WifiConfiguration network : retrievedNetworks) { 1639 assertEquals(2, network.linkedConfigurations.size()); 1640 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1641 if (otherNetwork == network) { 1642 continue; 1643 } 1644 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1645 } 1646 } 1647 } 1648 1649 /** 1650 * Verifies the linking of networks does not happen for non WPA networks when they have scan 1651 * results with same first 16 ASCII of bssid in 1652 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1653 */ 1654 @Test 1655 public void testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks() { 1656 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 1657 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1658 verifyAddNetworkToWifiConfigManager(network1); 1659 verifyAddNetworkToWifiConfigManager(network2); 1660 1661 // Create scan results with bssid which is different in only the last char. 1662 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1663 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1664 1665 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1666 networkScanDetail1)); 1667 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1668 networkScanDetail2)); 1669 1670 List<WifiConfiguration> retrievedNetworks = 1671 mWifiConfigManager.getConfiguredNetworks(); 1672 for (WifiConfiguration network : retrievedNetworks) { 1673 assertNull(network.linkedConfigurations); 1674 } 1675 } 1676 1677 /** 1678 * Verifies the linking of networks does not happen for networks with more than 1679 * {@link WifiConfigManager#LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES} scan 1680 * results with same first 16 ASCII of bssid in 1681 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1682 */ 1683 @Test 1684 public void testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize() { 1685 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1686 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1687 verifyAddNetworkToWifiConfigManager(network1); 1688 verifyAddNetworkToWifiConfigManager(network2); 1689 1690 // Create 7 scan results with bssid which is different in only the last char. 1691 String test_bssid_base = "af:89:56:34:56:6"; 1692 int scan_result_num = 0; 1693 for (; scan_result_num < WifiConfigManager.LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES + 1; 1694 scan_result_num++) { 1695 ScanDetail networkScanDetail = 1696 createScanDetailForNetwork( 1697 network1, test_bssid_base + Integer.toString(scan_result_num)); 1698 assertNotNull( 1699 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1700 networkScanDetail)); 1701 } 1702 1703 // Now add 1 scan result to the other network with bssid which is different in only the 1704 // last char. 1705 ScanDetail networkScanDetail2 = 1706 createScanDetailForNetwork( 1707 network2, test_bssid_base + Integer.toString(scan_result_num++)); 1708 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1709 networkScanDetail2)); 1710 1711 List<WifiConfiguration> retrievedNetworks = 1712 mWifiConfigManager.getConfiguredNetworks(); 1713 for (WifiConfiguration network : retrievedNetworks) { 1714 assertNull(network.linkedConfigurations); 1715 } 1716 } 1717 1718 /** 1719 * Verifies the linking of networks when they have scan results with same first 16 ASCII of 1720 * bssid in {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)} 1721 * and then subsequently delinked when the networks have default gateway set which do not match. 1722 */ 1723 @Test 1724 public void testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress() { 1725 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1726 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1727 verifyAddNetworkToWifiConfigManager(network1); 1728 verifyAddNetworkToWifiConfigManager(network2); 1729 1730 // Create scan results with bssid which is different in only the last char. 1731 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1732 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1733 1734 // Now save all these scan details corresponding to each of this network and expect 1735 // all of these networks to be linked with each other. 1736 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1737 networkScanDetail1)); 1738 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1739 networkScanDetail2)); 1740 1741 List<WifiConfiguration> retrievedNetworks = 1742 mWifiConfigManager.getConfiguredNetworks(); 1743 for (WifiConfiguration network : retrievedNetworks) { 1744 assertEquals(1, network.linkedConfigurations.size()); 1745 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1746 if (otherNetwork == network) { 1747 continue; 1748 } 1749 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1750 } 1751 } 1752 1753 // Now Set different GW mac address for both the networks and ensure they're unlinked. 1754 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1755 network1.networkId, "de:ad:fe:45:23:34")); 1756 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1757 network2.networkId, "ad:de:fe:45:23:34")); 1758 1759 // Add some dummy scan results again to re-evaluate the linking of networks. 1760 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1761 createScanDetailForNetwork(network1, "af:89:56:34:45:67"))); 1762 assertNotNull(mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1763 createScanDetailForNetwork(network1, "af:89:56:34:45:68"))); 1764 1765 retrievedNetworks = mWifiConfigManager.getConfiguredNetworks(); 1766 for (WifiConfiguration network : retrievedNetworks) { 1767 assertNull(network.linkedConfigurations); 1768 } 1769 } 1770 1771 /** 1772 * Verifies the creation of channel list using 1773 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)}. 1774 */ 1775 @Test 1776 public void testFetchChannelSetForNetwork() { 1777 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1778 verifyAddNetworkToWifiConfigManager(network); 1779 1780 // Create 5 scan results with different bssid's & frequencies. 1781 String test_bssid_base = "af:89:56:34:56:6"; 1782 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1783 ScanDetail networkScanDetail = 1784 createScanDetailForNetwork( 1785 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1786 assertNotNull( 1787 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1788 networkScanDetail)); 1789 1790 } 1791 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1792 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network.networkId, 1, 1793 TEST_FREQ_LIST[4])); 1794 } 1795 1796 /** 1797 * Verifies the creation of channel list using 1798 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1799 * ensures that the frequenecy of the currently connected network is in the returned 1800 * channel set. 1801 */ 1802 @Test 1803 public void testFetchChannelSetForNetworkIncludeCurrentNetwork() { 1804 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1805 verifyAddNetworkToWifiConfigManager(network); 1806 1807 // Create 5 scan results with different bssid's & frequencies. 1808 String test_bssid_base = "af:89:56:34:56:6"; 1809 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1810 ScanDetail networkScanDetail = 1811 createScanDetailForNetwork( 1812 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1813 assertNotNull( 1814 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1815 networkScanDetail)); 1816 1817 } 1818 1819 // Currently connected network frequency 2427 is not in the TEST_FREQ_LIST 1820 Set<Integer> freqs = mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1821 network.networkId, 1, 2427); 1822 1823 assertEquals(true, freqs.contains(2427)); 1824 } 1825 1826 /** 1827 * Verifies the creation of channel list using 1828 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1829 * ensures that scan results which have a timestamp beyond the provided age are not used 1830 * in the channel list. 1831 */ 1832 @Test 1833 public void testFetchChannelSetForNetworkIgnoresStaleScanResults() { 1834 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1835 verifyAddNetworkToWifiConfigManager(network); 1836 1837 long wallClockBase = 0; 1838 // Create 5 scan results with different bssid's & frequencies. 1839 String test_bssid_base = "af:89:56:34:56:6"; 1840 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1841 // Increment the seen value in the scan results for each of them. 1842 when(mClock.getWallClockMillis()).thenReturn(wallClockBase + i); 1843 ScanDetail networkScanDetail = 1844 createScanDetailForNetwork( 1845 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1846 assertNotNull( 1847 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1848 networkScanDetail)); 1849 1850 } 1851 int ageInMillis = 4; 1852 // Now fetch only scan results which are 4 millis stale. This should ignore the first 1853 // scan result. 1854 assertEquals( 1855 new HashSet<>(Arrays.asList( 1856 Arrays.copyOfRange( 1857 TEST_FREQ_LIST, 1858 TEST_FREQ_LIST.length - ageInMillis, TEST_FREQ_LIST.length))), 1859 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1860 network.networkId, ageInMillis, TEST_FREQ_LIST[4])); 1861 } 1862 1863 /** 1864 * Verifies the creation of channel list using 1865 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1866 * ensures that the list size does not exceed the max configured for the device. 1867 */ 1868 @Test 1869 public void testFetchChannelSetForNetworkIsLimitedToConfiguredSize() { 1870 // Need to recreate the WifiConfigManager instance for this test to modify the config 1871 // value which is read only in the constructor. 1872 int maxListSize = 3; 1873 mResources.setInteger( 1874 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 1875 maxListSize); 1876 createWifiConfigManager(); 1877 1878 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1879 verifyAddNetworkToWifiConfigManager(network); 1880 1881 // Create 5 scan results with different bssid's & frequencies. 1882 String test_bssid_base = "af:89:56:34:56:6"; 1883 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1884 ScanDetail networkScanDetail = 1885 createScanDetailForNetwork( 1886 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1887 assertNotNull( 1888 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1889 networkScanDetail)); 1890 1891 } 1892 // Ensure that the fetched list size is limited. 1893 assertEquals(maxListSize, 1894 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1895 network.networkId, 1, TEST_FREQ_LIST[4]).size()); 1896 } 1897 1898 /** 1899 * Verifies the creation of channel list using 1900 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1901 * ensures that scan results from linked networks are used in the channel list. 1902 */ 1903 @Test 1904 public void testFetchChannelSetForNetworkIncludesLinkedNetworks() { 1905 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1906 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1907 verifyAddNetworkToWifiConfigManager(network1); 1908 verifyAddNetworkToWifiConfigManager(network2); 1909 1910 String test_bssid_base = "af:89:56:34:56:6"; 1911 int TEST_FREQ_LISTIdx = 0; 1912 // Create 3 scan results with different bssid's & frequencies for network 1. 1913 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) { 1914 ScanDetail networkScanDetail = 1915 createScanDetailForNetwork( 1916 network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1917 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1918 assertNotNull( 1919 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1920 networkScanDetail)); 1921 1922 } 1923 // Create 3 scan results with different bssid's & frequencies for network 2. 1924 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) { 1925 ScanDetail networkScanDetail = 1926 createScanDetailForNetwork( 1927 network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1928 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1929 assertNotNull( 1930 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1931 networkScanDetail)); 1932 } 1933 1934 // Link the 2 configurations together using the GwMacAddress. 1935 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1936 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1937 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1938 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1939 1940 // The channel list fetched should include scan results from both the linked networks. 1941 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1942 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network1.networkId, 1, 1943 TEST_FREQ_LIST[0])); 1944 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1945 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network2.networkId, 1, 1946 TEST_FREQ_LIST[0])); 1947 } 1948 1949 /** 1950 * Verifies the creation of channel list using 1951 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1952 * ensures that scan results from linked networks are used in the channel list and that the 1953 * list size does not exceed the max configured for the device. 1954 */ 1955 @Test 1956 public void testFetchChannelSetForNetworkIncludesLinkedNetworksIsLimitedToConfiguredSize() { 1957 // Need to recreate the WifiConfigManager instance for this test to modify the config 1958 // value which is read only in the constructor. 1959 int maxListSize = 3; 1960 mResources.setInteger( 1961 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 1962 maxListSize); 1963 1964 createWifiConfigManager(); 1965 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1966 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1967 verifyAddNetworkToWifiConfigManager(network1); 1968 verifyAddNetworkToWifiConfigManager(network2); 1969 1970 String test_bssid_base = "af:89:56:34:56:6"; 1971 int TEST_FREQ_LISTIdx = 0; 1972 // Create 3 scan results with different bssid's & frequencies for network 1. 1973 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) { 1974 ScanDetail networkScanDetail = 1975 createScanDetailForNetwork( 1976 network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1977 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1978 assertNotNull( 1979 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1980 networkScanDetail)); 1981 1982 } 1983 // Create 3 scan results with different bssid's & frequencies for network 2. 1984 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) { 1985 ScanDetail networkScanDetail = 1986 createScanDetailForNetwork( 1987 network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1988 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1989 assertNotNull( 1990 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache( 1991 networkScanDetail)); 1992 } 1993 1994 // Link the 2 configurations together using the GwMacAddress. 1995 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1996 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1997 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1998 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1999 2000 // Ensure that the fetched list size is limited. 2001 assertEquals(maxListSize, 2002 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 2003 network1.networkId, 1, TEST_FREQ_LIST[0]).size()); 2004 assertEquals(maxListSize, 2005 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 2006 network2.networkId, 1, TEST_FREQ_LIST[0]).size()); 2007 } 2008 2009 /** 2010 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2011 * and ensures that any shared private networks networkId is not changed. 2012 * Test scenario: 2013 * 1. Load the shared networks from shared store and user 1 store. 2014 * 2. Switch to user 2 and ensure that the shared network's Id is not changed. 2015 */ 2016 @Test 2017 public void testHandleUserSwitchDoesNotChangeSharedNetworksId() throws Exception { 2018 int user1 = TEST_DEFAULT_USER; 2019 int user2 = TEST_DEFAULT_USER + 1; 2020 setupUserProfiles(user2); 2021 2022 int appId = 674; 2023 2024 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 2025 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 2026 user1Network.shared = false; 2027 user1Network.creatorUid = UserHandle.getUid(user1, appId); 2028 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2029 user2Network.shared = false; 2030 user2Network.creatorUid = UserHandle.getUid(user2, appId); 2031 final WifiConfiguration sharedNetwork1 = WifiConfigurationTestUtil.createPskNetwork(); 2032 final WifiConfiguration sharedNetwork2 = WifiConfigurationTestUtil.createPskNetwork(); 2033 2034 // Set up the store data that is loaded initially. 2035 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2036 { 2037 add(sharedNetwork1); 2038 add(sharedNetwork2); 2039 } 2040 }; 2041 List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() { 2042 { 2043 add(user1Network); 2044 } 2045 }; 2046 setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>()); 2047 assertTrue(mWifiConfigManager.loadFromStore()); 2048 verify(mWifiConfigStore).read(); 2049 2050 // Fetch the network ID's assigned to the shared networks initially. 2051 int sharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID; 2052 int sharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID; 2053 List<WifiConfiguration> retrievedNetworks = 2054 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2055 for (WifiConfiguration network : retrievedNetworks) { 2056 if (network.configKey().equals(sharedNetwork1.configKey())) { 2057 sharedNetwork1Id = network.networkId; 2058 } else if (network.configKey().equals(sharedNetwork2.configKey())) { 2059 sharedNetwork2Id = network.networkId; 2060 } 2061 } 2062 assertTrue(sharedNetwork1Id != WifiConfiguration.INVALID_NETWORK_ID); 2063 assertTrue(sharedNetwork2Id != WifiConfiguration.INVALID_NETWORK_ID); 2064 2065 // Set up the user 2 store data that is loaded at user switch. 2066 List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() { 2067 { 2068 add(user2Network); 2069 } 2070 }; 2071 setupStoreDataForUserRead(user2Networks, new HashSet<String>()); 2072 // Now switch the user to user 2 and ensure that shared network's IDs have not changed. 2073 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2074 mWifiConfigManager.handleUserSwitch(user2); 2075 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2076 2077 // Again fetch the network ID's assigned to the shared networks and ensure they have not 2078 // changed. 2079 int updatedSharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID; 2080 int updatedSharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID; 2081 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2082 for (WifiConfiguration network : retrievedNetworks) { 2083 if (network.configKey().equals(sharedNetwork1.configKey())) { 2084 updatedSharedNetwork1Id = network.networkId; 2085 } else if (network.configKey().equals(sharedNetwork2.configKey())) { 2086 updatedSharedNetwork2Id = network.networkId; 2087 } 2088 } 2089 assertEquals(sharedNetwork1Id, updatedSharedNetwork1Id); 2090 assertEquals(sharedNetwork2Id, updatedSharedNetwork2Id); 2091 } 2092 2093 /** 2094 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2095 * and ensures that any old user private networks are not visible anymore. 2096 * Test scenario: 2097 * 1. Load the shared networks from shared store and user 1 store. 2098 * 2. Switch to user 2 and ensure that the user 1's private network has been removed. 2099 */ 2100 @Test 2101 public void testHandleUserSwitchRemovesOldUserPrivateNetworks() throws Exception { 2102 int user1 = TEST_DEFAULT_USER; 2103 int user2 = TEST_DEFAULT_USER + 1; 2104 setupUserProfiles(user2); 2105 2106 int appId = 674; 2107 2108 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 2109 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 2110 user1Network.shared = false; 2111 user1Network.creatorUid = UserHandle.getUid(user1, appId); 2112 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2113 user2Network.shared = false; 2114 user2Network.creatorUid = UserHandle.getUid(user2, appId); 2115 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2116 2117 // Set up the store data that is loaded initially. 2118 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2119 { 2120 add(sharedNetwork); 2121 } 2122 }; 2123 List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() { 2124 { 2125 add(user1Network); 2126 } 2127 }; 2128 setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>()); 2129 assertTrue(mWifiConfigManager.loadFromStore()); 2130 verify(mWifiConfigStore).read(); 2131 2132 // Fetch the network ID assigned to the user 1 network initially. 2133 int user1NetworkId = WifiConfiguration.INVALID_NETWORK_ID; 2134 List<WifiConfiguration> retrievedNetworks = 2135 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2136 for (WifiConfiguration network : retrievedNetworks) { 2137 if (network.configKey().equals(user1Network.configKey())) { 2138 user1NetworkId = network.networkId; 2139 } 2140 } 2141 2142 // Set up the user 2 store data that is loaded at user switch. 2143 List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() { 2144 { 2145 add(user2Network); 2146 } 2147 }; 2148 setupStoreDataForUserRead(user2Networks, new HashSet<String>()); 2149 // Now switch the user to user 2 and ensure that user 1's private network has been removed. 2150 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2151 Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2); 2152 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2153 assertTrue((removedNetworks.size() == 1) && (removedNetworks.contains(user1NetworkId))); 2154 2155 // Set the expected networks to be |sharedNetwork| and |user2Network|. 2156 List<WifiConfiguration> expectedNetworks = new ArrayList<WifiConfiguration>() { 2157 { 2158 add(sharedNetwork); 2159 add(user2Network); 2160 } 2161 }; 2162 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2163 expectedNetworks, mWifiConfigManager.getConfiguredNetworksWithPasswords()); 2164 2165 // Send another user switch indication with the same user 2. This should be ignored and 2166 // hence should not remove any new networks. 2167 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2168 removedNetworks = mWifiConfigManager.handleUserSwitch(user2); 2169 assertTrue(removedNetworks.isEmpty()); 2170 } 2171 2172 /** 2173 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2174 * and ensures that user switch from a user with no private networks is handled. 2175 * Test scenario: 2176 * 1. Load the shared networks from shared store and emptu user 1 store. 2177 * 2. Switch to user 2 and ensure that no private networks were removed. 2178 */ 2179 @Test 2180 public void testHandleUserSwitchWithNoOldUserPrivateNetworks() throws Exception { 2181 int user1 = TEST_DEFAULT_USER; 2182 int user2 = TEST_DEFAULT_USER + 1; 2183 setupUserProfiles(user2); 2184 2185 int appId = 674; 2186 2187 // Create 2 networks. 1 for user2 and 1 shared. 2188 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2189 user2Network.shared = false; 2190 user2Network.creatorUid = UserHandle.getUid(user2, appId); 2191 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2192 2193 // Set up the store data that is loaded initially. 2194 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2195 { 2196 add(sharedNetwork); 2197 } 2198 }; 2199 setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(), 2200 new HashSet<String>()); 2201 assertTrue(mWifiConfigManager.loadFromStore()); 2202 verify(mWifiConfigStore).read(); 2203 2204 // Set up the user 2 store data that is loaded at user switch. 2205 List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() { 2206 { 2207 add(user2Network); 2208 } 2209 }; 2210 setupStoreDataForUserRead(user2Networks, new HashSet<String>()); 2211 // Now switch the user to user 2 and ensure that no private network has been removed. 2212 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2213 Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2); 2214 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2215 assertTrue(removedNetworks.isEmpty()); 2216 } 2217 2218 /** 2219 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2220 * and ensures that any non current user private networks are moved to shared store file. 2221 * This test simulates the following test case: 2222 * 1. Loads the shared networks from shared store at bootup. 2223 * 2. Load the private networks from user store on user 1 unlock. 2224 * 3. Switch to user 2 and ensure that the user 2's private network has been moved to user 2's 2225 * private store file. 2226 */ 2227 @Test 2228 public void testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore() throws Exception { 2229 int user1 = TEST_DEFAULT_USER; 2230 int user2 = TEST_DEFAULT_USER + 1; 2231 setupUserProfiles(user2); 2232 2233 int appId = 674; 2234 2235 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 2236 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 2237 user1Network.shared = false; 2238 user1Network.creatorUid = UserHandle.getUid(user1, appId); 2239 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2240 user2Network.shared = false; 2241 user2Network.creatorUid = UserHandle.getUid(user2, appId); 2242 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2243 2244 // Set up the shared store data that is loaded at bootup. User 2's private network 2245 // is still in shared store because they have not yet logged-in after upgrade. 2246 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2247 { 2248 add(sharedNetwork); 2249 add(user2Network); 2250 } 2251 }; 2252 setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(), 2253 new HashSet<String>()); 2254 assertTrue(mWifiConfigManager.loadFromStore()); 2255 verify(mWifiConfigStore).read(); 2256 2257 // Set up the user store data that is loaded at user unlock. 2258 List<WifiConfiguration> userNetworks = new ArrayList<WifiConfiguration>() { 2259 { 2260 add(user1Network); 2261 } 2262 }; 2263 setupStoreDataForUserRead(userNetworks, new HashSet<String>()); 2264 mWifiConfigManager.handleUserUnlock(user1); 2265 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2266 // Capture the written data for the user 1 and ensure that it corresponds to what was 2267 // setup. 2268 Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList = 2269 captureWriteNetworksListStoreData(); 2270 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2271 sharedNetworks, writtenNetworkList.first); 2272 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2273 userNetworks, writtenNetworkList.second); 2274 2275 // Now switch the user to user2 and ensure that user 2's private network has been moved to 2276 // the user store. 2277 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2278 mWifiConfigManager.handleUserSwitch(user2); 2279 // Set the expected network list before comparing. user1Network should be in shared data. 2280 // Note: In the real world, user1Network will no longer be visible now because it should 2281 // already be in user1's private store file. But, we're purposefully exposing it 2282 // via |loadStoreData| to test if other user's private networks are pushed to shared store. 2283 List<WifiConfiguration> expectedSharedNetworks = new ArrayList<WifiConfiguration>() { 2284 { 2285 add(sharedNetwork); 2286 add(user1Network); 2287 } 2288 }; 2289 List<WifiConfiguration> expectedUserNetworks = new ArrayList<WifiConfiguration>() { 2290 { 2291 add(user2Network); 2292 } 2293 }; 2294 // Capture the first written data triggered for saving the old user's network 2295 // configurations. 2296 writtenNetworkList = captureWriteNetworksListStoreData(); 2297 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2298 sharedNetworks, writtenNetworkList.first); 2299 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2300 userNetworks, writtenNetworkList.second); 2301 2302 // Now capture the next written data triggered after the switch and ensure that user 2's 2303 // network is now in user store data. 2304 writtenNetworkList = captureWriteNetworksListStoreData(); 2305 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2306 expectedSharedNetworks, writtenNetworkList.first); 2307 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2308 expectedUserNetworks, writtenNetworkList.second); 2309 } 2310 2311 /** 2312 * Verify that unlocking an user that owns a legacy Passpoint configuration (which is stored 2313 * temporarily in the share store) will migrate it to PasspointManager and removed from 2314 * the list of configured networks. 2315 * 2316 * @throws Exception 2317 */ 2318 @Test 2319 public void testHandleUserUnlockRemovePasspointConfigFromSharedConfig() throws Exception { 2320 int user1 = TEST_DEFAULT_USER; 2321 int appId = 674; 2322 2323 final WifiConfiguration passpointConfig = 2324 WifiConfigurationTestUtil.createPasspointNetwork(); 2325 passpointConfig.creatorUid = UserHandle.getUid(user1, appId); 2326 passpointConfig.isLegacyPasspointConfig = true; 2327 2328 // Set up the shared store data to contain one legacy Passpoint configuration. 2329 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2330 { 2331 add(passpointConfig); 2332 } 2333 }; 2334 setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(), 2335 new HashSet<String>()); 2336 assertTrue(mWifiConfigManager.loadFromStore()); 2337 verify(mWifiConfigStore).read(); 2338 assertEquals(1, mWifiConfigManager.getConfiguredNetworks().size()); 2339 2340 // Unlock the owner of the legacy Passpoint configuration, verify it is removed from 2341 // the configured networks (migrated to PasspointManager). 2342 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2343 mWifiConfigManager.handleUserUnlock(user1); 2344 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2345 Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList = 2346 captureWriteNetworksListStoreData(); 2347 assertTrue(writtenNetworkList.first.isEmpty()); 2348 assertTrue(writtenNetworkList.second.isEmpty()); 2349 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2350 } 2351 2352 /** 2353 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2354 * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is 2355 * read immediately if the user is unlocked during the switch. 2356 */ 2357 @Test 2358 public void testHandleUserSwitchWhenUnlocked() throws Exception { 2359 int user1 = TEST_DEFAULT_USER; 2360 int user2 = TEST_DEFAULT_USER + 1; 2361 setupUserProfiles(user2); 2362 2363 // Set up the internal data first. 2364 assertTrue(mWifiConfigManager.loadFromStore()); 2365 2366 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2367 // user2 is unlocked and switched to foreground. 2368 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2369 mWifiConfigManager.handleUserSwitch(user2); 2370 // Ensure that the read was invoked. 2371 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2372 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2373 } 2374 2375 /** 2376 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2377 * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not 2378 * read until the user is unlocked. 2379 */ 2380 public void testHandleUserSwitchWhenLocked() throws Exception { 2381 int user1 = TEST_DEFAULT_USER; 2382 int user2 = TEST_DEFAULT_USER + 1; 2383 setupUserProfiles(user2); 2384 2385 // Set up the internal data first. 2386 assertTrue(mWifiConfigManager.loadFromStore()); 2387 2388 // user2 is locked and switched to foreground. 2389 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2390 mWifiConfigManager.handleUserSwitch(user2); 2391 2392 // Ensure that the read was not invoked. 2393 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2394 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2395 2396 // Now try unlocking some other user (user1), this should be ignored. 2397 mWifiConfigManager.handleUserUnlock(user1); 2398 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2399 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2400 2401 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2402 // Unlock the user2 and ensure that we read the data now. 2403 mWifiConfigManager.handleUserUnlock(user2); 2404 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2405 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2406 } 2407 2408 /** 2409 * Verifies that the foreground user stop using {@link WifiConfigManager#handleUserStop(int)} 2410 * and ensures that the store is written only when the foreground user is stopped. 2411 */ 2412 @Test 2413 public void testHandleUserStop() throws Exception { 2414 int user1 = TEST_DEFAULT_USER; 2415 int user2 = TEST_DEFAULT_USER + 1; 2416 setupUserProfiles(user2); 2417 2418 // Try stopping background user2 first, this should not do anything. 2419 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2420 mWifiConfigManager.handleUserStop(user2); 2421 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2422 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2423 2424 // Now try stopping the foreground user1, this should trigger a write to store. 2425 mWifiConfigManager.handleUserStop(user1); 2426 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2427 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2428 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 2429 } 2430 2431 /** 2432 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2433 * results in a store read after bootup. 2434 */ 2435 @Test 2436 public void testHandleUserUnlockAfterBootup() throws Exception { 2437 int user1 = TEST_DEFAULT_USER; 2438 2439 // Set up the internal data first. 2440 assertTrue(mWifiConfigManager.loadFromStore()); 2441 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 2442 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2443 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2444 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2445 2446 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2447 // Unlock the user1 (default user) for the first time and ensure that we read the data. 2448 mWifiConfigManager.handleUserUnlock(user1); 2449 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 2450 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2451 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2452 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 2453 } 2454 2455 /** 2456 * Verifies that the store read after bootup received after 2457 * foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2458 * results in a user store read. 2459 */ 2460 @Test 2461 public void testHandleBootupAfterUserUnlock() throws Exception { 2462 int user1 = TEST_DEFAULT_USER; 2463 2464 // Unlock the user1 (default user) for the first time and ensure that we don't read the 2465 // data. 2466 mWifiConfigManager.handleUserUnlock(user1); 2467 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 2468 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2469 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2470 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2471 2472 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2473 // Read from store now. 2474 assertTrue(mWifiConfigManager.loadFromStore()); 2475 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2476 .setUserStore(any(WifiConfigStore.StoreFile.class)); 2477 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 2478 } 2479 2480 /** 2481 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} does 2482 * not always result in a store read unless the user had switched or just booted up. 2483 */ 2484 @Test 2485 public void testHandleUserUnlockWithoutSwitchOrBootup() throws Exception { 2486 int user1 = TEST_DEFAULT_USER; 2487 int user2 = TEST_DEFAULT_USER + 1; 2488 setupUserProfiles(user2); 2489 2490 // Set up the internal data first. 2491 assertTrue(mWifiConfigManager.loadFromStore()); 2492 2493 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2494 // user2 is unlocked and switched to foreground. 2495 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2496 mWifiConfigManager.handleUserSwitch(user2); 2497 // Ensure that the read was invoked. 2498 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2499 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2500 2501 // Unlock the user2 again and ensure that we don't read the data now. 2502 mWifiConfigManager.handleUserUnlock(user2); 2503 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2504 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2505 } 2506 2507 /** 2508 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserSwitch(int)} 2509 * is ignored if the legacy store migration is not complete. 2510 */ 2511 @Test 2512 public void testHandleUserSwitchAfterBootupBeforeLegacyStoreMigration() throws Exception { 2513 int user2 = TEST_DEFAULT_USER + 1; 2514 2515 // Switch to user2 for the first time and ensure that we don't read or 2516 // write the store files. 2517 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2518 mWifiConfigManager.handleUserSwitch(user2); 2519 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2520 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2521 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2522 } 2523 2524 /** 2525 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2526 * is ignored if the legacy store migration is not complete. 2527 */ 2528 @Test 2529 public void testHandleUserUnlockAfterBootupBeforeLegacyStoreMigration() throws Exception { 2530 int user1 = TEST_DEFAULT_USER; 2531 2532 // Unlock the user1 (default user) for the first time and ensure that we don't read or 2533 // write the store files. 2534 mWifiConfigManager.handleUserUnlock(user1); 2535 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2536 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2537 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2538 } 2539 2540 /** 2541 * Verifies the private network addition using 2542 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 2543 * by a non foreground user is rejected. 2544 */ 2545 @Test 2546 public void testAddNetworkUsingBackgroundUserUId() throws Exception { 2547 int user2 = TEST_DEFAULT_USER + 1; 2548 setupUserProfiles(user2); 2549 2550 int creatorUid = UserHandle.getUid(user2, 674); 2551 2552 // Create a network for user2 try adding it. This should be rejected. 2553 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2554 NetworkUpdateResult result = addNetworkToWifiConfigManager(user2Network, creatorUid); 2555 assertFalse(result.isSuccess()); 2556 } 2557 2558 /** 2559 * Verifies the private network addition using 2560 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 2561 * by SysUI is always accepted. 2562 */ 2563 @Test 2564 public void testAddNetworkUsingSysUiUid() throws Exception { 2565 // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile| 2566 int user2 = TEST_DEFAULT_USER + 1; 2567 setupUserProfiles(user2); 2568 2569 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2570 mWifiConfigManager.handleUserSwitch(user2); 2571 2572 // Create a network for user2 try adding it. This should be rejected. 2573 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2574 NetworkUpdateResult result = addNetworkToWifiConfigManager(user2Network, TEST_SYSUI_UID); 2575 assertTrue(result.isSuccess()); 2576 } 2577 2578 /** 2579 * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does 2580 * not attempt to read from any of the stores (new or legacy) when the store files are 2581 * not present. 2582 */ 2583 @Test 2584 public void testFreshInstallDoesNotLoadFromStore() throws Exception { 2585 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 2586 2587 assertTrue(mWifiConfigManager.loadFromStore()); 2588 2589 verify(mWifiConfigStore, never()).read(); 2590 2591 assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty()); 2592 } 2593 2594 /** 2595 * Verifies the user switch using {@link WifiConfigManager#handleUserSwitch(int)} is handled 2596 * when the store files (new or legacy) are not present. 2597 */ 2598 @Test 2599 public void testHandleUserSwitchAfterFreshInstall() throws Exception { 2600 int user2 = TEST_DEFAULT_USER + 1; 2601 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 2602 2603 assertTrue(mWifiConfigManager.loadFromStore()); 2604 verify(mWifiConfigStore, never()).read(); 2605 2606 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2607 // Now switch the user to user 2. 2608 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2609 mWifiConfigManager.handleUserSwitch(user2); 2610 // Ensure that the read was invoked. 2611 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2612 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2613 } 2614 2615 /** 2616 * Verifies that the last user selected network parameter is set when 2617 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set 2618 * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or 2619 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID. 2620 */ 2621 @Test 2622 public void testLastSelectedNetwork() throws Exception { 2623 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 2624 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 2625 2626 when(mClock.getElapsedSinceBootMillis()).thenReturn(67L); 2627 assertTrue(mWifiConfigManager.enableNetwork( 2628 result.getNetworkId(), true, TEST_CREATOR_UID)); 2629 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 2630 assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp()); 2631 2632 // Now disable the network and ensure that the last selected flag is cleared. 2633 assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 2634 assertEquals( 2635 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 2636 2637 // Enable it again and remove the network to ensure that the last selected flag was cleared. 2638 assertTrue(mWifiConfigManager.enableNetwork( 2639 result.getNetworkId(), true, TEST_CREATOR_UID)); 2640 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 2641 assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey()); 2642 2643 assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 2644 assertEquals( 2645 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 2646 } 2647 2648 /** 2649 * Verifies that all the networks for the provided app is removed when 2650 * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked. 2651 */ 2652 @Test 2653 public void testRemoveNetworksForApp() throws Exception { 2654 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 2655 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 2656 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 2657 2658 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2659 2660 ApplicationInfo app = new ApplicationInfo(); 2661 app.uid = TEST_CREATOR_UID; 2662 app.packageName = TEST_CREATOR_NAME; 2663 assertEquals(3, mWifiConfigManager.removeNetworksForApp(app).size()); 2664 2665 // Ensure all the networks are removed now. 2666 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2667 } 2668 2669 /** 2670 * Verifies that all the networks for the provided user is removed when 2671 * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked. 2672 */ 2673 @Test 2674 public void testRemoveNetworksForUser() throws Exception { 2675 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 2676 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 2677 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 2678 2679 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2680 2681 assertEquals(3, mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER).size()); 2682 2683 // Ensure all the networks are removed now. 2684 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2685 } 2686 2687 /** 2688 * Verifies that the connect choice is removed from all networks when 2689 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked. 2690 */ 2691 @Test 2692 public void testRemoveNetworkRemovesConnectChoice() throws Exception { 2693 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 2694 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 2695 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 2696 verifyAddNetworkToWifiConfigManager(network1); 2697 verifyAddNetworkToWifiConfigManager(network2); 2698 verifyAddNetworkToWifiConfigManager(network3); 2699 2700 // Set connect choice of network 2 over network 1. 2701 assertTrue( 2702 mWifiConfigManager.setNetworkConnectChoice( 2703 network1.networkId, network2.configKey(), 78L)); 2704 2705 WifiConfiguration retrievedNetwork = 2706 mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2707 assertEquals( 2708 network2.configKey(), 2709 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2710 2711 // Remove network 3 and ensure that the connect choice on network 1 is not removed. 2712 assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID)); 2713 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2714 assertEquals( 2715 network2.configKey(), 2716 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2717 2718 // Now remove network 2 and ensure that the connect choice on network 1 is removed.. 2719 assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID)); 2720 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2721 assertNotEquals( 2722 network2.configKey(), 2723 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2724 2725 // This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for 2726 // clearing it after network removal. 2727 mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(eq(false)); 2728 } 2729 2730 /** 2731 * Verifies that all the ephemeral and passpoint networks are removed when 2732 * {@link WifiConfigManager#removeAllEphemeralOrPasspointConfiguredNetworks()} is invoked. 2733 */ 2734 @Test 2735 public void testRemoveAllEphemeralOrPasspointConfiguredNetworks() throws Exception { 2736 WifiConfiguration savedOpenNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 2737 WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createEphemeralNetwork(); 2738 WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork(); 2739 2740 verifyAddNetworkToWifiConfigManager(savedOpenNetwork); 2741 verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork); 2742 verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork); 2743 2744 List<WifiConfiguration> expectedConfigsBeforeRemove = new ArrayList<WifiConfiguration>() {{ 2745 add(savedOpenNetwork); 2746 add(ephemeralNetwork); 2747 add(passpointNetwork); 2748 }}; 2749 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2750 expectedConfigsBeforeRemove, mWifiConfigManager.getConfiguredNetworks()); 2751 2752 assertTrue(mWifiConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks()); 2753 2754 List<WifiConfiguration> expectedConfigsAfterRemove = new ArrayList<WifiConfiguration>() {{ 2755 add(savedOpenNetwork); 2756 }}; 2757 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2758 expectedConfigsAfterRemove, mWifiConfigManager.getConfiguredNetworks()); 2759 2760 // No more ephemeral or passpoint networks to remove now. 2761 assertFalse(mWifiConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks()); 2762 } 2763 2764 /** 2765 * Verifies that the modification of a single network using 2766 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any 2767 * updates to the network config in 2768 * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected 2769 * in the internal database. 2770 */ 2771 @Test 2772 public void testUpdateSingleNetworkWithKeysUpdate() { 2773 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 2774 network.enterpriseConfig = 2775 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 2776 verifyAddNetworkToWifiConfigManager(network); 2777 2778 // Now verify that network configurations match before we make any change. 2779 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2780 network, 2781 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2782 2783 // Modify the network ca_cert field in updateNetworkKeys method during a network 2784 // config update. 2785 final String newCaCertAlias = "test"; 2786 assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias()); 2787 2788 doAnswer(new AnswerWithArguments() { 2789 public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) { 2790 newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2791 return true; 2792 } 2793 }).when(mWifiKeyStore).updateNetworkKeys( 2794 any(WifiConfiguration.class), any(WifiConfiguration.class)); 2795 2796 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 2797 2798 // Now verify that the keys update is reflected in the configuration fetched from internal 2799 // db. 2800 network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2801 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2802 network, 2803 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2804 } 2805 2806 /** 2807 * Verifies that the dump method prints out all the saved network details with passwords masked. 2808 * {@link WifiConfigManager#dump(FileDescriptor, PrintWriter, String[])}. 2809 */ 2810 @Test 2811 public void testDump() { 2812 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2813 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 2814 eapNetwork.enterpriseConfig.setPassword("blah"); 2815 2816 verifyAddNetworkToWifiConfigManager(pskNetwork); 2817 verifyAddNetworkToWifiConfigManager(eapNetwork); 2818 2819 StringWriter stringWriter = new StringWriter(); 2820 mWifiConfigManager.dump( 2821 new FileDescriptor(), new PrintWriter(stringWriter), new String[0]); 2822 String dumpString = stringWriter.toString(); 2823 2824 // Ensure that the network SSIDs were dumped out. 2825 assertTrue(dumpString.contains(pskNetwork.SSID)); 2826 assertTrue(dumpString.contains(eapNetwork.SSID)); 2827 2828 // Ensure that the network passwords were not dumped out. 2829 assertFalse(dumpString.contains(pskNetwork.preSharedKey)); 2830 assertFalse(dumpString.contains(eapNetwork.enterpriseConfig.getPassword())); 2831 } 2832 2833 /** 2834 * Verifies the ordering of network list generated using 2835 * {@link WifiConfigManager#retrieveHiddenNetworkList()}. 2836 */ 2837 @Test 2838 public void testRetrieveHiddenList() { 2839 // Create and add 3 networks. 2840 WifiConfiguration network1 = WifiConfigurationTestUtil.createWepHiddenNetwork(); 2841 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskHiddenNetwork(); 2842 WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2843 verifyAddNetworkToWifiConfigManager(network1); 2844 verifyAddNetworkToWifiConfigManager(network2); 2845 verifyAddNetworkToWifiConfigManager(network3); 2846 2847 // Enable all of them. 2848 assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID)); 2849 assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID)); 2850 assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID)); 2851 2852 // Now set scan results in 2 of them to set the corresponding 2853 // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field. 2854 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 2855 network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54)); 2856 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 2857 network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54)); 2858 2859 // Now increment |network3|'s association count. This should ensure that this network 2860 // is preferred over |network1|. 2861 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId)); 2862 2863 // Retrieve the hidden network list & verify the order of the networks returned. 2864 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = 2865 mWifiConfigManager.retrieveHiddenNetworkList(); 2866 assertEquals(3, hiddenNetworks.size()); 2867 assertEquals(network3.SSID, hiddenNetworks.get(0).ssid); 2868 assertEquals(network1.SSID, hiddenNetworks.get(1).ssid); 2869 assertEquals(network2.SSID, hiddenNetworks.get(2).ssid); 2870 2871 // Now permanently disable |network3|. This should remove network 3 from the list. 2872 assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID)); 2873 2874 // Retrieve the hidden network list again & verify the order of the networks returned. 2875 hiddenNetworks = mWifiConfigManager.retrieveHiddenNetworkList(); 2876 assertEquals(2, hiddenNetworks.size()); 2877 assertEquals(network1.SSID, hiddenNetworks.get(0).ssid); 2878 assertEquals(network2.SSID, hiddenNetworks.get(1).ssid); 2879 } 2880 2881 /** 2882 * Verifies the addition of network configurations using 2883 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and 2884 * default key mgmt does not add duplicate network configs. 2885 */ 2886 @Test 2887 public void testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt() { 2888 final String ssid = "\"test_blah\""; 2889 // Add a network with the above SSID and default key mgmt and ensure it was added 2890 // successfully. 2891 WifiConfiguration network1 = new WifiConfiguration(); 2892 network1.SSID = ssid; 2893 NetworkUpdateResult result = addNetworkToWifiConfigManager(network1); 2894 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2895 assertTrue(result.isNewNetwork()); 2896 2897 List<WifiConfiguration> retrievedNetworks = 2898 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2899 assertEquals(1, retrievedNetworks.size()); 2900 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2901 network1, retrievedNetworks.get(0)); 2902 2903 // Now add a second network with the same SSID and default key mgmt and ensure that it 2904 // didn't add a new duplicate network. 2905 WifiConfiguration network2 = new WifiConfiguration(); 2906 network2.SSID = ssid; 2907 result = addNetworkToWifiConfigManager(network2); 2908 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2909 assertFalse(result.isNewNetwork()); 2910 2911 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2912 assertEquals(1, retrievedNetworks.size()); 2913 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2914 network2, retrievedNetworks.get(0)); 2915 } 2916 2917 /** 2918 * Verifies the addition of network configurations using 2919 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and 2920 * different key mgmt should add different network configs. 2921 */ 2922 @Test 2923 public void testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt() { 2924 final String ssid = "\"test_blah\""; 2925 // Add a network with the above SSID and WPA_PSK key mgmt and ensure it was added 2926 // successfully. 2927 WifiConfiguration network1 = new WifiConfiguration(); 2928 network1.SSID = ssid; 2929 network1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 2930 network1.preSharedKey = "\"test_blah\""; 2931 NetworkUpdateResult result = addNetworkToWifiConfigManager(network1); 2932 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2933 assertTrue(result.isNewNetwork()); 2934 2935 List<WifiConfiguration> retrievedNetworks = 2936 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2937 assertEquals(1, retrievedNetworks.size()); 2938 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2939 network1, retrievedNetworks.get(0)); 2940 2941 // Now add a second network with the same SSID and NONE key mgmt and ensure that it 2942 // does add a new network. 2943 WifiConfiguration network2 = new WifiConfiguration(); 2944 network2.SSID = ssid; 2945 network2.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 2946 result = addNetworkToWifiConfigManager(network2); 2947 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2948 assertTrue(result.isNewNetwork()); 2949 2950 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2951 assertEquals(2, retrievedNetworks.size()); 2952 List<WifiConfiguration> networks = Arrays.asList(network1, network2); 2953 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2954 networks, retrievedNetworks); 2955 } 2956 2957 /** 2958 * Verifies that adding a network with a proxy, without having permission OVERRIDE_WIFI_CONFIG, 2959 * holding device policy, or profile owner policy fails. 2960 */ 2961 @Test 2962 public void testAddNetworkWithProxyFails() { 2963 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2964 false, // withNetworkSettings 2965 false, // withProfileOwnerPolicy 2966 false, // withDeviceOwnerPolicy 2967 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2968 false, // assertSuccess 2969 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2970 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2971 false, // withNetworkSettings 2972 false, // withProfileOwnerPolicy 2973 false, // withDeviceOwnerPolicy 2974 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2975 false, // assertSuccess 2976 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2977 } 2978 2979 /** 2980 * Verifies that adding a network with a PAC or STATIC proxy with permission 2981 * OVERRIDE_WIFI_CONFIG is successful 2982 */ 2983 @Test 2984 public void testAddNetworkWithProxyWithConfOverride() { 2985 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2986 true, // withNetworkSettings 2987 false, // withProfileOwnerPolicy 2988 false, // withDeviceOwnerPolicy 2989 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2990 true, // assertSuccess 2991 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2992 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2993 true, // withNetworkSettings 2994 false, // withProfileOwnerPolicy 2995 false, // withDeviceOwnerPolicy 2996 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2997 true, // assertSuccess 2998 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2999 } 3000 3001 /** 3002 * Verifies that adding a network with a PAC or STATIC proxy, while holding policy 3003 * {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER} is successful 3004 */ 3005 @Test 3006 public void testAddNetworkWithProxyAsProfileOwner() { 3007 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3008 false, // withNetworkSettings 3009 true, // withProfileOwnerPolicy 3010 false, // withDeviceOwnerPolicy 3011 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3012 true, // assertSuccess 3013 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3014 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3015 false, // withNetworkSettings 3016 true, // withProfileOwnerPolicy 3017 false, // withDeviceOwnerPolicy 3018 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3019 true, // assertSuccess 3020 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3021 } 3022 /** 3023 * Verifies that adding a network with a PAC or STATIC proxy, while holding policy 3024 * {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER} is successful 3025 */ 3026 @Test 3027 public void testAddNetworkWithProxyAsDeviceOwner() { 3028 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3029 false, // withNetworkSettings 3030 false, // withProfileOwnerPolicy 3031 true, // withDeviceOwnerPolicy 3032 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3033 true, // assertSuccess 3034 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3035 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3036 false, // withNetworkSettings 3037 false, // withProfileOwnerPolicy 3038 true, // withDeviceOwnerPolicy 3039 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3040 true, // assertSuccess 3041 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3042 } 3043 /** 3044 * Verifies that updating a network (that has no proxy) and adding a PAC or STATIC proxy fails 3045 * without being able to override configs, or holding Device or Profile owner policies. 3046 */ 3047 @Test 3048 public void testUpdateNetworkAddProxyFails() { 3049 WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3050 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 3051 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3052 false, // withNetworkSettings 3053 false, // withProfileOwnerPolicy 3054 false, // withDeviceOwnerPolicy 3055 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3056 false, // assertSuccess 3057 result.getNetworkId()); // Update networkID 3058 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3059 false, // withNetworkSettings 3060 false, // withProfileOwnerPolicy 3061 false, // withDeviceOwnerPolicy 3062 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3063 false, // assertSuccess 3064 result.getNetworkId()); // Update networkID 3065 } 3066 /** 3067 * Verifies that updating a network and adding a proxy is successful in the cases where app can 3068 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3069 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3070 * otherwise. 3071 */ 3072 @Test 3073 public void testUpdateNetworkAddProxyWithPermissionAndSystem() { 3074 // Testing updating network with uid permission OVERRIDE_WIFI_CONFIG 3075 WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3076 NetworkUpdateResult result = addNetworkToWifiConfigManager(network, TEST_CREATOR_UID); 3077 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3078 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3079 true, // withNetworkSettings 3080 false, // withProfileOwnerPolicy 3081 false, // withDeviceOwnerPolicy 3082 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3083 true, // assertSuccess 3084 result.getNetworkId()); // Update networkID 3085 3086 // Testing updating network with proxy while holding Profile Owner policy 3087 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3088 result = addNetworkToWifiConfigManager(network, TEST_NO_PERM_UID); 3089 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3090 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3091 false, // withNetworkSettings 3092 true, // withProfileOwnerPolicy 3093 false, // withDeviceOwnerPolicy 3094 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3095 true, // assertSuccess 3096 result.getNetworkId()); // Update networkID 3097 3098 // Testing updating network with proxy while holding Device Owner Policy 3099 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3100 result = addNetworkToWifiConfigManager(network, TEST_NO_PERM_UID); 3101 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3102 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3103 false, // withNetworkSettings 3104 false, // withProfileOwnerPolicy 3105 true, // withDeviceOwnerPolicy 3106 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3107 true, // assertSuccess 3108 result.getNetworkId()); // Update networkID 3109 } 3110 3111 /** 3112 * Verifies that updating a network that has a proxy without changing the proxy, can succeed 3113 * without proxy specific permissions. 3114 */ 3115 @Test 3116 public void testUpdateNetworkUnchangedProxy() { 3117 IpConfiguration ipConf = WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(); 3118 // First create a WifiConfiguration with proxy 3119 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3120 false, // withNetworkSettings 3121 true, // withProfileOwnerPolicy 3122 false, // withDeviceOwnerPolicy 3123 ipConf, 3124 true, // assertSuccess 3125 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3126 // Update the network while using the same ipConf, and no proxy specific permissions 3127 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3128 false, // withNetworkSettings 3129 false, // withProfileOwnerPolicy 3130 false, // withDeviceOwnerPolicy 3131 ipConf, 3132 true, // assertSuccess 3133 result.getNetworkId()); // Update networkID 3134 } 3135 3136 /** 3137 * Verifies that updating a network with a different proxy succeeds in the cases where app can 3138 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3139 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3140 * otherwise. 3141 */ 3142 @Test 3143 public void testUpdateNetworkDifferentProxy() { 3144 // Create two proxy configurations of the same type, but different values 3145 IpConfiguration ipConf1 = 3146 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3147 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3148 TEST_STATIC_PROXY_HOST_1, 3149 TEST_STATIC_PROXY_PORT_1, 3150 TEST_STATIC_PROXY_EXCLUSION_LIST_1, 3151 TEST_PAC_PROXY_LOCATION_1); 3152 IpConfiguration ipConf2 = 3153 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3154 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3155 TEST_STATIC_PROXY_HOST_2, 3156 TEST_STATIC_PROXY_PORT_2, 3157 TEST_STATIC_PROXY_EXCLUSION_LIST_2, 3158 TEST_PAC_PROXY_LOCATION_2); 3159 3160 // Update with Conf Override 3161 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3162 true, // withNetworkSettings 3163 false, // withProfileOwnerPolicy 3164 false, // withDeviceOwnerPolicy 3165 ipConf1, 3166 true, // assertSuccess 3167 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3168 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3169 true, // withNetworkSettings 3170 false, // withProfileOwnerPolicy 3171 false, // withDeviceOwnerPolicy 3172 ipConf2, 3173 true, // assertSuccess 3174 result.getNetworkId()); // Update networkID 3175 3176 // Update as Device Owner 3177 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3178 false, // withNetworkSettings 3179 false, // withProfileOwnerPolicy 3180 true, // withDeviceOwnerPolicy 3181 ipConf1, 3182 true, // assertSuccess 3183 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3184 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3185 false, // withNetworkSettings 3186 false, // withProfileOwnerPolicy 3187 true, // withDeviceOwnerPolicy 3188 ipConf2, 3189 true, // assertSuccess 3190 result.getNetworkId()); // Update networkID 3191 3192 // Update as Profile Owner 3193 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3194 false, // withNetworkSettings 3195 true, // withProfileOwnerPolicy 3196 false, // withDeviceOwnerPolicy 3197 ipConf1, 3198 true, // assertSuccess 3199 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3200 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3201 false, // withNetworkSettings 3202 true, // withProfileOwnerPolicy 3203 false, // withDeviceOwnerPolicy 3204 ipConf2, 3205 true, // assertSuccess 3206 result.getNetworkId()); // Update networkID 3207 3208 // Update with no permissions (should fail) 3209 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3210 false, // withNetworkSettings 3211 true, // withProfileOwnerPolicy 3212 false, // withDeviceOwnerPolicy 3213 ipConf1, 3214 true, // assertSuccess 3215 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3216 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3217 false, // withNetworkSettings 3218 false, // withProfileOwnerPolicy 3219 false, // withDeviceOwnerPolicy 3220 ipConf2, 3221 false, // assertSuccess 3222 result.getNetworkId()); // Update networkID 3223 } 3224 /** 3225 * Verifies that updating a network removing its proxy succeeds in the cases where app can 3226 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3227 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3228 * otherwise. 3229 */ 3230 @Test 3231 public void testUpdateNetworkRemoveProxy() { 3232 // Create two different IP configurations, one with a proxy and another without. 3233 IpConfiguration ipConf1 = 3234 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3235 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3236 TEST_STATIC_PROXY_HOST_1, 3237 TEST_STATIC_PROXY_PORT_1, 3238 TEST_STATIC_PROXY_EXCLUSION_LIST_1, 3239 TEST_PAC_PROXY_LOCATION_1); 3240 IpConfiguration ipConf2 = 3241 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3242 WifiConfigurationTestUtil.NONE_PROXY_SETTING, 3243 TEST_STATIC_PROXY_HOST_2, 3244 TEST_STATIC_PROXY_PORT_2, 3245 TEST_STATIC_PROXY_EXCLUSION_LIST_2, 3246 TEST_PAC_PROXY_LOCATION_2); 3247 3248 // Update with Conf Override 3249 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3250 true, // withNetworkSettings 3251 false, // withProfileOwnerPolicy 3252 false, // withDeviceOwnerPolicy 3253 ipConf1, 3254 true, // assertSuccess 3255 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3256 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3257 true, // withNetworkSettings 3258 false, // withProfileOwnerPolicy 3259 false, // withDeviceOwnerPolicy 3260 ipConf2, 3261 true, // assertSuccess 3262 result.getNetworkId()); // Update networkID 3263 3264 // Update as Device Owner 3265 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3266 false, // withNetworkSettings 3267 false, // withProfileOwnerPolicy 3268 true, // withDeviceOwnerPolicy 3269 ipConf1, 3270 true, // assertSuccess 3271 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3272 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3273 false, // withNetworkSettings 3274 false, // withProfileOwnerPolicy 3275 true, // withDeviceOwnerPolicy 3276 ipConf2, 3277 true, // assertSuccess 3278 result.getNetworkId()); // Update networkID 3279 3280 // Update as Profile Owner 3281 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3282 false, // withNetworkSettings 3283 true, // withProfileOwnerPolicy 3284 false, // withDeviceOwnerPolicy 3285 ipConf1, 3286 true, // assertSuccess 3287 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3288 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3289 false, // withNetworkSettings 3290 true, // withProfileOwnerPolicy 3291 false, // withDeviceOwnerPolicy 3292 ipConf2, 3293 true, // assertSuccess 3294 result.getNetworkId()); // Update networkID 3295 3296 // Update with no permissions (should fail) 3297 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3298 false, // withNetworkSettings 3299 true, // withProfileOwnerPolicy 3300 false, // withDeviceOwnerPolicy 3301 ipConf1, 3302 true, // assertSuccess 3303 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3304 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3305 false, // withNetworkSettings 3306 false, // withProfileOwnerPolicy 3307 false, // withDeviceOwnerPolicy 3308 ipConf2, 3309 false, // assertSuccess 3310 result.getNetworkId()); // Update networkID 3311 } 3312 3313 /** 3314 * Verifies that the app specified BSSID is converted and saved in lower case. 3315 */ 3316 @Test 3317 public void testAppSpecifiedBssidIsSavedInLowerCase() { 3318 final String bssid = "0A:08:5C:BB:89:6D"; // upper case 3319 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 3320 openNetwork.BSSID = bssid; 3321 3322 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 3323 3324 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork( 3325 result.getNetworkId()); 3326 3327 assertNotEquals(retrievedNetwork.BSSID, bssid); 3328 assertEquals(retrievedNetwork.BSSID, bssid.toLowerCase()); 3329 } 3330 3331 private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3332 boolean withNetworkSettings, 3333 boolean withProfileOwnerPolicy, 3334 boolean withDeviceOwnerPolicy, 3335 IpConfiguration ipConfiguration, 3336 boolean assertSuccess, 3337 int networkId) { 3338 WifiConfiguration network; 3339 if (networkId == WifiConfiguration.INVALID_NETWORK_ID) { 3340 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3341 } else { 3342 network = mWifiConfigManager.getConfiguredNetwork(networkId); 3343 } 3344 network.setIpConfiguration(ipConfiguration); 3345 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 3346 eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))) 3347 .thenReturn(withProfileOwnerPolicy); 3348 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 3349 eq(DeviceAdminInfo.USES_POLICY_DEVICE_OWNER))) 3350 .thenReturn(withDeviceOwnerPolicy); 3351 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())) 3352 .thenReturn(withNetworkSettings); 3353 int uid = withNetworkSettings ? TEST_CREATOR_UID : TEST_NO_PERM_UID; 3354 NetworkUpdateResult result = addNetworkToWifiConfigManager(network, uid); 3355 assertEquals(assertSuccess, result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3356 return result; 3357 } 3358 3359 private void createWifiConfigManager() { 3360 mWifiConfigManager = 3361 new WifiConfigManager( 3362 mContext, mClock, mUserManager, mTelephonyManager, 3363 mWifiKeyStore, mWifiConfigStore, 3364 mWifiPermissionsUtil, mWifiPermissionsWrapper, mNetworkListStoreData, 3365 mDeletedEphemeralSsidsStoreData); 3366 mWifiConfigManager.enableVerboseLogging(1); 3367 } 3368 3369 /** 3370 * This method sets defaults in the provided WifiConfiguration object if not set 3371 * so that it can be used for comparison with the configuration retrieved from 3372 * WifiConfigManager. 3373 */ 3374 private void setDefaults(WifiConfiguration configuration) { 3375 if (configuration.allowedAuthAlgorithms.isEmpty()) { 3376 configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 3377 } 3378 if (configuration.allowedProtocols.isEmpty()) { 3379 configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 3380 configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 3381 } 3382 if (configuration.allowedKeyManagement.isEmpty()) { 3383 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 3384 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); 3385 } 3386 if (configuration.allowedPairwiseCiphers.isEmpty()) { 3387 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 3388 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 3389 } 3390 if (configuration.allowedGroupCiphers.isEmpty()) { 3391 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 3392 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 3393 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 3394 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); 3395 } 3396 if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) { 3397 configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP); 3398 } 3399 if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) { 3400 configuration.setProxySettings(IpConfiguration.ProxySettings.NONE); 3401 } 3402 configuration.status = WifiConfiguration.Status.DISABLED; 3403 configuration.getNetworkSelectionStatus().setNetworkSelectionStatus( 3404 NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED); 3405 } 3406 3407 /** 3408 * Modifies the provided configuration with creator uid, package name 3409 * and time. 3410 */ 3411 private void setCreationDebugParams(WifiConfiguration configuration) { 3412 configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID; 3413 configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME; 3414 configuration.creationTime = configuration.updateTime = 3415 WifiConfigManager.createDebugTimeStampString( 3416 TEST_WALLCLOCK_CREATION_TIME_MILLIS); 3417 } 3418 3419 /** 3420 * Modifies the provided configuration with update uid, package name 3421 * and time. 3422 */ 3423 private void setUpdateDebugParams(WifiConfiguration configuration) { 3424 configuration.lastUpdateUid = TEST_UPDATE_UID; 3425 configuration.lastUpdateName = TEST_UPDATE_NAME; 3426 configuration.updateTime = 3427 WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 3428 } 3429 3430 private void assertNotEquals(Object expected, Object actual) { 3431 if (actual != null) { 3432 assertFalse(actual.equals(expected)); 3433 } else { 3434 assertNotNull(expected); 3435 } 3436 } 3437 3438 /** 3439 * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that 3440 * the existing |BSSID| field is not the same value as the one being set 3441 */ 3442 private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) { 3443 assertNotEquals(bssid, configuration.BSSID); 3444 configuration.BSSID = bssid; 3445 } 3446 3447 /** 3448 * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also, 3449 * asserts that the existing |mIpConfiguration| field is not the same value as the one being set 3450 */ 3451 private void assertAndSetNetworkIpConfiguration( 3452 WifiConfiguration configuration, IpConfiguration ipConfiguration) { 3453 assertNotEquals(ipConfiguration, configuration.getIpConfiguration()); 3454 configuration.setIpConfiguration(ipConfiguration); 3455 } 3456 3457 /** 3458 * Modifies the provided WifiConfiguration with the specified |wepKeys| value and 3459 * |wepTxKeyIndex|. 3460 */ 3461 private void assertAndSetNetworkWepKeysAndTxIndex( 3462 WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) { 3463 assertNotEquals(wepKeys, configuration.wepKeys); 3464 assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex); 3465 configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length); 3466 configuration.wepTxKeyIndex = wepTxKeyIdx; 3467 } 3468 3469 /** 3470 * Modifies the provided WifiConfiguration with the specified |preSharedKey| value. 3471 */ 3472 private void assertAndSetNetworkPreSharedKey( 3473 WifiConfiguration configuration, String preSharedKey) { 3474 assertNotEquals(preSharedKey, configuration.preSharedKey); 3475 configuration.preSharedKey = preSharedKey; 3476 } 3477 3478 /** 3479 * Modifies the provided WifiConfiguration with the specified enteprise |password| value. 3480 */ 3481 private void assertAndSetNetworkEnterprisePassword( 3482 WifiConfiguration configuration, String password) { 3483 assertNotEquals(password, configuration.enterpriseConfig.getPassword()); 3484 configuration.enterpriseConfig.setPassword(password); 3485 } 3486 3487 /** 3488 * Helper method to capture the networks list store data that will be written by 3489 * WifiConfigStore.write() method. 3490 */ 3491 private Pair<List<WifiConfiguration>, List<WifiConfiguration>> 3492 captureWriteNetworksListStoreData() { 3493 try { 3494 ArgumentCaptor<ArrayList> sharedConfigsCaptor = 3495 ArgumentCaptor.forClass(ArrayList.class); 3496 ArgumentCaptor<ArrayList> userConfigsCaptor = 3497 ArgumentCaptor.forClass(ArrayList.class); 3498 mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData) 3499 .setSharedConfigurations(sharedConfigsCaptor.capture()); 3500 mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData) 3501 .setUserConfigurations(userConfigsCaptor.capture()); 3502 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 3503 return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue()); 3504 } catch (Exception e) { 3505 fail("Exception encountered during write " + e); 3506 } 3507 return null; 3508 } 3509 3510 /** 3511 * Returns whether the provided network was in the store data or not. 3512 */ 3513 private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) { 3514 Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData = 3515 captureWriteNetworksListStoreData(); 3516 if (networkListStoreData == null) { 3517 return false; 3518 } 3519 List<WifiConfiguration> networkList = new ArrayList<>(); 3520 networkList.addAll(networkListStoreData.first); 3521 networkList.addAll(networkListStoreData.second); 3522 return isNetworkInConfigStoreData(configuration, networkList); 3523 } 3524 3525 /** 3526 * Returns whether the provided network was in the store data or not. 3527 */ 3528 private boolean isNetworkInConfigStoreData( 3529 WifiConfiguration configuration, List<WifiConfiguration> networkList) { 3530 boolean foundNetworkInStoreData = false; 3531 for (WifiConfiguration retrievedConfig : networkList) { 3532 if (retrievedConfig.configKey().equals(configuration.configKey())) { 3533 foundNetworkInStoreData = true; 3534 break; 3535 } 3536 } 3537 return foundNetworkInStoreData; 3538 } 3539 3540 /** 3541 * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData 3542 * after WifiConfigStore#read. 3543 */ 3544 private void setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations, 3545 List<WifiConfiguration> userConfigurations, Set<String> deletedEphemeralSsids) { 3546 when(mNetworkListStoreData.getSharedConfigurations()) 3547 .thenReturn(sharedConfigurations); 3548 when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations); 3549 when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids); 3550 } 3551 3552 /** 3553 * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData 3554 * after WifiConfigStore#switchUserStoreAndRead. 3555 */ 3556 private void setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations, 3557 Set<String> deletedEphemeralSsids) { 3558 when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations); 3559 when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids); 3560 } 3561 3562 /** 3563 * Verifies that the provided network was not present in the last config store write. 3564 */ 3565 private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) { 3566 assertFalse(isNetworkInConfigStoreData(configuration)); 3567 } 3568 3569 /** 3570 * Verifies that the provided network was present in the last config store write. 3571 */ 3572 private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) { 3573 assertTrue(isNetworkInConfigStoreData(configuration)); 3574 } 3575 3576 private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) { 3577 if (!TextUtils.isEmpty(configuration.preSharedKey)) { 3578 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey); 3579 } 3580 if (configuration.wepKeys != null) { 3581 for (int i = 0; i < configuration.wepKeys.length; i++) { 3582 if (!TextUtils.isEmpty(configuration.wepKeys[i])) { 3583 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]); 3584 } 3585 } 3586 } 3587 if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) { 3588 assertEquals( 3589 WifiConfigManager.PASSWORD_MASK, 3590 configuration.enterpriseConfig.getPassword()); 3591 } 3592 } 3593 3594 /** 3595 * Verifies that the network was present in the network change broadcast and returns the 3596 * change reason. 3597 */ 3598 private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) { 3599 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 3600 ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class); 3601 mContextConfigStoreMockOrder.verify(mContext) 3602 .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture()); 3603 3604 assertEquals(userHandleCaptor.getValue(), UserHandle.ALL); 3605 Intent intent = intentCaptor.getValue(); 3606 3607 int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1); 3608 WifiConfiguration retrievedConfig = 3609 (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION); 3610 assertEquals(retrievedConfig.configKey(), configuration.configKey()); 3611 3612 // Verify that all the passwords are masked in the broadcast configuration. 3613 assertPasswordsMaskedInWifiConfiguration(retrievedConfig); 3614 3615 return changeReason; 3616 } 3617 3618 /** 3619 * Verifies that we sent out an add broadcast with the provided network. 3620 */ 3621 private void verifyNetworkAddBroadcast(WifiConfiguration configuration) { 3622 assertEquals( 3623 verifyNetworkInBroadcastAndReturnReason(configuration), 3624 WifiManager.CHANGE_REASON_ADDED); 3625 } 3626 3627 /** 3628 * Verifies that we sent out an update broadcast with the provided network. 3629 */ 3630 private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) { 3631 assertEquals( 3632 verifyNetworkInBroadcastAndReturnReason(configuration), 3633 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 3634 } 3635 3636 /** 3637 * Verifies that we sent out a remove broadcast with the provided network. 3638 */ 3639 private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) { 3640 assertEquals( 3641 verifyNetworkInBroadcastAndReturnReason(configuration), 3642 WifiManager.CHANGE_REASON_REMOVED); 3643 } 3644 3645 private void verifyWifiConfigStoreRead() { 3646 assertTrue(mWifiConfigManager.loadFromStore()); 3647 mContextConfigStoreMockOrder.verify(mContext) 3648 .sendBroadcastAsUser(any(Intent.class), any(UserHandle.class)); 3649 } 3650 3651 private void triggerStoreReadIfNeeded() { 3652 // Trigger a store read if not already done. 3653 if (!mStoreReadTriggered) { 3654 verifyWifiConfigStoreRead(); 3655 mStoreReadTriggered = true; 3656 } 3657 } 3658 3659 /** 3660 * Adds the provided configuration to WifiConfigManager with uid = TEST_CREATOR_UID. 3661 */ 3662 private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) { 3663 return addNetworkToWifiConfigManager(configuration, TEST_CREATOR_UID); 3664 } 3665 3666 /** 3667 * Adds the provided configuration to WifiConfigManager and modifies the provided configuration 3668 * with creator/update uid, package name and time. This also sets defaults for fields not 3669 * populated. 3670 * These fields are populated internally by WifiConfigManager and hence we need 3671 * to modify the configuration before we compare the added network with the retrieved network. 3672 * This method also triggers a store read if not already done. 3673 */ 3674 private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration, 3675 int uid) { 3676 clearInvocations(mContext, mWifiConfigStore, mNetworkListStoreData); 3677 triggerStoreReadIfNeeded(); 3678 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS); 3679 NetworkUpdateResult result = 3680 mWifiConfigManager.addOrUpdateNetwork(configuration, uid); 3681 setDefaults(configuration); 3682 setCreationDebugParams(configuration); 3683 configuration.networkId = result.getNetworkId(); 3684 return result; 3685 } 3686 3687 /** 3688 * Add network to WifiConfigManager and ensure that it was successful. 3689 */ 3690 private NetworkUpdateResult verifyAddNetworkToWifiConfigManager( 3691 WifiConfiguration configuration) { 3692 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3693 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3694 assertTrue(result.isNewNetwork()); 3695 assertTrue(result.hasIpChanged()); 3696 assertTrue(result.hasProxyChanged()); 3697 3698 verifyNetworkAddBroadcast(configuration); 3699 // Verify that the config store write was triggered with this new configuration. 3700 verifyNetworkInConfigStoreData(configuration); 3701 return result; 3702 } 3703 3704 /** 3705 * Add ephemeral network to WifiConfigManager and ensure that it was successful. 3706 */ 3707 private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager( 3708 WifiConfiguration configuration) throws Exception { 3709 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3710 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3711 assertTrue(result.isNewNetwork()); 3712 assertTrue(result.hasIpChanged()); 3713 assertTrue(result.hasProxyChanged()); 3714 3715 verifyNetworkAddBroadcast(configuration); 3716 // Ensure that the write was not invoked for ephemeral network addition. 3717 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3718 return result; 3719 } 3720 3721 /** 3722 * Add Passpoint network to WifiConfigManager and ensure that it was successful. 3723 */ 3724 private NetworkUpdateResult verifyAddPasspointNetworkToWifiConfigManager( 3725 WifiConfiguration configuration) throws Exception { 3726 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3727 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3728 assertTrue(result.isNewNetwork()); 3729 assertTrue(result.hasIpChanged()); 3730 assertTrue(result.hasProxyChanged()); 3731 3732 // Verify keys are not being installed. 3733 verify(mWifiKeyStore, never()).updateNetworkKeys(any(WifiConfiguration.class), 3734 any(WifiConfiguration.class)); 3735 verifyNetworkAddBroadcast(configuration); 3736 // Ensure that the write was not invoked for Passpoint network addition. 3737 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3738 return result; 3739 } 3740 3741 /** 3742 * Updates the provided configuration to WifiConfigManager and modifies the provided 3743 * configuration with update uid, package name and time. 3744 * These fields are populated internally by WifiConfigManager and hence we need 3745 * to modify the configuration before we compare the added network with the retrieved network. 3746 */ 3747 private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) { 3748 clearInvocations(mContext, mWifiConfigStore, mNetworkListStoreData); 3749 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 3750 NetworkUpdateResult result = 3751 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID); 3752 setUpdateDebugParams(configuration); 3753 return result; 3754 } 3755 3756 /** 3757 * Update network to WifiConfigManager config change and ensure that it was successful. 3758 */ 3759 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager( 3760 WifiConfiguration configuration) { 3761 NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration); 3762 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3763 assertFalse(result.isNewNetwork()); 3764 3765 verifyNetworkUpdateBroadcast(configuration); 3766 // Verify that the config store write was triggered with this new configuration. 3767 verifyNetworkInConfigStoreData(configuration); 3768 return result; 3769 } 3770 3771 /** 3772 * Update network to WifiConfigManager without IP config change and ensure that it was 3773 * successful. 3774 */ 3775 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange( 3776 WifiConfiguration configuration) { 3777 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 3778 assertFalse(result.hasIpChanged()); 3779 assertFalse(result.hasProxyChanged()); 3780 return result; 3781 } 3782 3783 /** 3784 * Update network to WifiConfigManager with IP config change and ensure that it was 3785 * successful. 3786 */ 3787 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange( 3788 WifiConfiguration configuration) { 3789 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 3790 assertTrue(result.hasIpChanged()); 3791 assertTrue(result.hasProxyChanged()); 3792 return result; 3793 } 3794 3795 /** 3796 * Removes network from WifiConfigManager and ensure that it was successful. 3797 */ 3798 private void verifyRemoveNetworkFromWifiConfigManager( 3799 WifiConfiguration configuration) { 3800 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3801 3802 verifyNetworkRemoveBroadcast(configuration); 3803 // Verify if the config store write was triggered without this new configuration. 3804 verifyNetworkNotInConfigStoreData(configuration); 3805 } 3806 3807 /** 3808 * Removes ephemeral network from WifiConfigManager and ensure that it was successful. 3809 */ 3810 private void verifyRemoveEphemeralNetworkFromWifiConfigManager( 3811 WifiConfiguration configuration) throws Exception { 3812 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3813 3814 verifyNetworkRemoveBroadcast(configuration); 3815 // Ensure that the write was not invoked for ephemeral network remove. 3816 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3817 } 3818 3819 /** 3820 * Removes Passpoint network from WifiConfigManager and ensure that it was successful. 3821 */ 3822 private void verifyRemovePasspointNetworkFromWifiConfigManager( 3823 WifiConfiguration configuration) throws Exception { 3824 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3825 3826 // Verify keys are not being removed. 3827 verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class)); 3828 verifyNetworkRemoveBroadcast(configuration); 3829 // Ensure that the write was not invoked for Passpoint network remove. 3830 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3831 } 3832 3833 /** 3834 * Verifies the provided network's public status and ensures that the network change broadcast 3835 * has been sent out. 3836 */ 3837 private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) { 3838 assertEquals(status, configuration.status); 3839 verifyNetworkUpdateBroadcast(configuration); 3840 } 3841 3842 /** 3843 * Verifies the network's selection status update. 3844 * 3845 * For temporarily disabled reasons, the method ensures that the status has changed only if 3846 * disable reason counter has exceeded the threshold. 3847 * 3848 * For permanently disabled/enabled reasons, the method ensures that the public status has 3849 * changed and the network change broadcast has been sent out. 3850 */ 3851 private void verifyUpdateNetworkSelectionStatus( 3852 int networkId, int reason, int temporaryDisableReasonCounter) { 3853 when(mClock.getElapsedSinceBootMillis()) 3854 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS); 3855 3856 // Fetch the current status of the network before we try to update the status. 3857 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3858 NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus(); 3859 int currentDisableReason = currentStatus.getNetworkSelectionDisableReason(); 3860 3861 // First set the status to the provided reason. 3862 assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason)); 3863 3864 // Now fetch the network configuration and verify the new status of the network. 3865 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3866 3867 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 3868 int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason(); 3869 long retrievedDisableTime = retrievedStatus.getDisableTime(); 3870 int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason); 3871 int disableReasonThreshold = 3872 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason]; 3873 3874 if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) { 3875 assertEquals(reason, retrievedDisableReason); 3876 assertTrue(retrievedStatus.isNetworkEnabled()); 3877 assertEquals( 3878 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 3879 retrievedDisableTime); 3880 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 3881 } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) { 3882 // For temporarily disabled networks, we need to ensure that the current status remains 3883 // until the threshold is crossed. 3884 assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter); 3885 if (retrievedDisableReasonCounter < disableReasonThreshold) { 3886 assertEquals(currentDisableReason, retrievedDisableReason); 3887 assertEquals( 3888 currentStatus.getNetworkSelectionStatus(), 3889 retrievedStatus.getNetworkSelectionStatus()); 3890 } else { 3891 assertEquals(reason, retrievedDisableReason); 3892 assertTrue(retrievedStatus.isNetworkTemporaryDisabled()); 3893 assertEquals( 3894 TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime); 3895 } 3896 } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) { 3897 assertEquals(reason, retrievedDisableReason); 3898 assertTrue(retrievedStatus.isNetworkPermanentlyDisabled()); 3899 assertEquals( 3900 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 3901 retrievedDisableTime); 3902 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED); 3903 } 3904 } 3905 3906 /** 3907 * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency 3908 * values. 3909 */ 3910 private ScanDetail createScanDetailForNetwork( 3911 WifiConfiguration configuration, String bssid, int level, int frequency) { 3912 return WifiConfigurationTestUtil.createScanDetailForNetwork(configuration, bssid, level, 3913 frequency, mClock.getUptimeSinceBootMillis(), mClock.getWallClockMillis()); 3914 } 3915 /** 3916 * Creates a scan detail corresponding to the provided network and BSSID value. 3917 */ 3918 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) { 3919 return createScanDetailForNetwork(configuration, bssid, 0, 0); 3920 } 3921 3922 /** 3923 * Creates a scan detail corresponding to the provided network and fixed BSSID value. 3924 */ 3925 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) { 3926 return createScanDetailForNetwork(configuration, TEST_BSSID); 3927 } 3928 3929 /** 3930 * Adds the provided network and then creates a scan detail corresponding to the network. The 3931 * method then creates a ScanDetail corresponding to the network and ensures that the network 3932 * is properly matched using 3933 * {@link WifiConfigManager#getConfiguredNetworkForScanDetailAndCache(ScanDetail)} and also 3934 * verifies that the provided scan detail was cached, 3935 */ 3936 private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 3937 WifiConfiguration network) { 3938 // First add the provided network. 3939 verifyAddNetworkToWifiConfigManager(network); 3940 3941 // Now create a dummy scan detail corresponding to the network. 3942 ScanDetail scanDetail = createScanDetailForNetwork(network); 3943 ScanResult scanResult = scanDetail.getScanResult(); 3944 3945 WifiConfiguration retrievedNetwork = 3946 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(scanDetail); 3947 // Retrieve the network with password data for comparison. 3948 retrievedNetwork = 3949 mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId); 3950 3951 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 3952 network, retrievedNetwork); 3953 3954 // Now retrieve the scan detail cache and ensure that the new scan detail is in cache. 3955 ScanDetailCache retrievedScanDetailCache = 3956 mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId); 3957 assertEquals(1, retrievedScanDetailCache.size()); 3958 ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID); 3959 3960 ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult); 3961 } 3962 3963 /** 3964 * Adds a new network and verifies that the |HasEverConnected| flag is set to false. 3965 */ 3966 private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) { 3967 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 3968 WifiConfiguration retrievedNetwork = 3969 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 3970 assertFalse("Adding a new network should not have hasEverConnected set to true.", 3971 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 3972 } 3973 3974 /** 3975 * Updates an existing network with some credential change and verifies that the 3976 * |HasEverConnected| flag is set to false. 3977 */ 3978 private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse( 3979 WifiConfiguration network) { 3980 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 3981 WifiConfiguration retrievedNetwork = 3982 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 3983 assertFalse("Updating network credentials config should clear hasEverConnected.", 3984 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 3985 assertTrue(result.hasCredentialChanged()); 3986 } 3987 3988 /** 3989 * Updates an existing network after connection using 3990 * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the 3991 * |HasEverConnected| flag is set to true. 3992 */ 3993 private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) { 3994 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId)); 3995 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3996 assertTrue("hasEverConnected expected to be true after connection.", 3997 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 3998 } 3999 4000 /** 4001 * Sets up a user profiles for WifiConfigManager testing. 4002 * 4003 * @param userId Id of the user. 4004 */ 4005 private void setupUserProfiles(int userId) { 4006 final UserInfo userInfo = 4007 new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY); 4008 List<UserInfo> userProfiles = Arrays.asList(userInfo); 4009 when(mUserManager.getProfiles(userId)).thenReturn(userProfiles); 4010 when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true); 4011 } 4012 4013} 4014