WifiConfigManagerTest.java revision 988256f6c383c2c6b24d295c2f2e7ce77ec9955f
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 user stop handling 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 that the user stop handling using {@link WifiConfigManager#handleUserStop(int)} 2433 * and ensures that the shared data is not lost when the foreground user is stopped. 2434 */ 2435 @Test 2436 public void testHandleUserStopDoesNotClearSharedData() throws Exception { 2437 int user1 = TEST_DEFAULT_USER; 2438 2439 // 2440 // Setup the database for the user before initiating stop. 2441 // 2442 int appId = 674; 2443 // Create 2 networks. 1 for user1, and 1 shared. 2444 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 2445 user1Network.shared = false; 2446 user1Network.creatorUid = UserHandle.getUid(user1, appId); 2447 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2448 2449 // Set up the store data that is loaded initially. 2450 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2451 { 2452 add(sharedNetwork); 2453 } 2454 }; 2455 List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() { 2456 { 2457 add(user1Network); 2458 } 2459 }; 2460 setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>()); 2461 assertTrue(mWifiConfigManager.loadFromStore()); 2462 verify(mWifiConfigStore).read(); 2463 2464 // Ensure that we have 2 networks in the database before the stop. 2465 assertEquals(2, mWifiConfigManager.getConfiguredNetworks().size()); 2466 2467 mWifiConfigManager.handleUserStop(user1); 2468 2469 // Ensure that we only have 1 shared network in the database after the stop. 2470 assertEquals(1, mWifiConfigManager.getConfiguredNetworks().size()); 2471 assertEquals(sharedNetwork.SSID, mWifiConfigManager.getConfiguredNetworks().get(0).SSID); 2472 } 2473 2474 /** 2475 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2476 * results in a store read after bootup. 2477 */ 2478 @Test 2479 public void testHandleUserUnlockAfterBootup() throws Exception { 2480 int user1 = TEST_DEFAULT_USER; 2481 2482 // Set up the internal data first. 2483 assertTrue(mWifiConfigManager.loadFromStore()); 2484 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 2485 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2486 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2487 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2488 2489 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2490 // Unlock the user1 (default user) for the first time and ensure that we read the data. 2491 mWifiConfigManager.handleUserUnlock(user1); 2492 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 2493 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2494 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2495 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 2496 } 2497 2498 /** 2499 * Verifies that the store read after bootup received after 2500 * foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2501 * results in a user store read. 2502 */ 2503 @Test 2504 public void testHandleBootupAfterUserUnlock() throws Exception { 2505 int user1 = TEST_DEFAULT_USER; 2506 2507 // Unlock the user1 (default user) for the first time and ensure that we don't read the 2508 // data. 2509 mWifiConfigManager.handleUserUnlock(user1); 2510 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 2511 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2512 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2513 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2514 2515 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2516 // Read from store now. 2517 assertTrue(mWifiConfigManager.loadFromStore()); 2518 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2519 .setUserStore(any(WifiConfigStore.StoreFile.class)); 2520 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 2521 } 2522 2523 /** 2524 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} does 2525 * not always result in a store read unless the user had switched or just booted up. 2526 */ 2527 @Test 2528 public void testHandleUserUnlockWithoutSwitchOrBootup() throws Exception { 2529 int user1 = TEST_DEFAULT_USER; 2530 int user2 = TEST_DEFAULT_USER + 1; 2531 setupUserProfiles(user2); 2532 2533 // Set up the internal data first. 2534 assertTrue(mWifiConfigManager.loadFromStore()); 2535 2536 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2537 // user2 is unlocked and switched to foreground. 2538 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2539 mWifiConfigManager.handleUserSwitch(user2); 2540 // Ensure that the read was invoked. 2541 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2542 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2543 2544 // Unlock the user2 again and ensure that we don't read the data now. 2545 mWifiConfigManager.handleUserUnlock(user2); 2546 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2547 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2548 } 2549 2550 /** 2551 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserSwitch(int)} 2552 * is ignored if the legacy store migration is not complete. 2553 */ 2554 @Test 2555 public void testHandleUserSwitchAfterBootupBeforeLegacyStoreMigration() throws Exception { 2556 int user2 = TEST_DEFAULT_USER + 1; 2557 2558 // Switch to user2 for the first time and ensure that we don't read or 2559 // write the store files. 2560 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2561 mWifiConfigManager.handleUserSwitch(user2); 2562 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2563 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2564 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2565 } 2566 2567 /** 2568 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2569 * is ignored if the legacy store migration is not complete. 2570 */ 2571 @Test 2572 public void testHandleUserUnlockAfterBootupBeforeLegacyStoreMigration() throws Exception { 2573 int user1 = TEST_DEFAULT_USER; 2574 2575 // Unlock the user1 (default user) for the first time and ensure that we don't read or 2576 // write the store files. 2577 mWifiConfigManager.handleUserUnlock(user1); 2578 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2579 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2580 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2581 } 2582 2583 /** 2584 * Verifies the private network addition using 2585 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 2586 * by a non foreground user is rejected. 2587 */ 2588 @Test 2589 public void testAddNetworkUsingBackgroundUserUId() throws Exception { 2590 int user2 = TEST_DEFAULT_USER + 1; 2591 setupUserProfiles(user2); 2592 2593 int creatorUid = UserHandle.getUid(user2, 674); 2594 2595 // Create a network for user2 try adding it. This should be rejected. 2596 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2597 NetworkUpdateResult result = addNetworkToWifiConfigManager(user2Network, creatorUid); 2598 assertFalse(result.isSuccess()); 2599 } 2600 2601 /** 2602 * Verifies the private network addition using 2603 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 2604 * by SysUI is always accepted. 2605 */ 2606 @Test 2607 public void testAddNetworkUsingSysUiUid() throws Exception { 2608 // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile| 2609 int user2 = TEST_DEFAULT_USER + 1; 2610 setupUserProfiles(user2); 2611 2612 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2613 mWifiConfigManager.handleUserSwitch(user2); 2614 2615 // Create a network for user2 try adding it. This should be rejected. 2616 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2617 NetworkUpdateResult result = addNetworkToWifiConfigManager(user2Network, TEST_SYSUI_UID); 2618 assertTrue(result.isSuccess()); 2619 } 2620 2621 /** 2622 * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does 2623 * not attempt to read from any of the stores (new or legacy) when the store files are 2624 * not present. 2625 */ 2626 @Test 2627 public void testFreshInstallDoesNotLoadFromStore() throws Exception { 2628 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 2629 2630 assertTrue(mWifiConfigManager.loadFromStore()); 2631 2632 verify(mWifiConfigStore, never()).read(); 2633 2634 assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty()); 2635 } 2636 2637 /** 2638 * Verifies the user switch using {@link WifiConfigManager#handleUserSwitch(int)} is handled 2639 * when the store files (new or legacy) are not present. 2640 */ 2641 @Test 2642 public void testHandleUserSwitchAfterFreshInstall() throws Exception { 2643 int user2 = TEST_DEFAULT_USER + 1; 2644 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 2645 2646 assertTrue(mWifiConfigManager.loadFromStore()); 2647 verify(mWifiConfigStore, never()).read(); 2648 2649 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2650 // Now switch the user to user 2. 2651 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2652 mWifiConfigManager.handleUserSwitch(user2); 2653 // Ensure that the read was invoked. 2654 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2655 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2656 } 2657 2658 /** 2659 * Verifies that the last user selected network parameter is set when 2660 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set 2661 * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or 2662 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID. 2663 */ 2664 @Test 2665 public void testLastSelectedNetwork() throws Exception { 2666 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 2667 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 2668 2669 when(mClock.getElapsedSinceBootMillis()).thenReturn(67L); 2670 assertTrue(mWifiConfigManager.enableNetwork( 2671 result.getNetworkId(), true, TEST_CREATOR_UID)); 2672 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 2673 assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp()); 2674 2675 // Now disable the network and ensure that the last selected flag is cleared. 2676 assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 2677 assertEquals( 2678 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 2679 2680 // Enable it again and remove the network to ensure that the last selected flag was cleared. 2681 assertTrue(mWifiConfigManager.enableNetwork( 2682 result.getNetworkId(), true, TEST_CREATOR_UID)); 2683 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 2684 assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey()); 2685 2686 assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 2687 assertEquals( 2688 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 2689 } 2690 2691 /** 2692 * Verifies that all the networks for the provided app is removed when 2693 * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked. 2694 */ 2695 @Test 2696 public void testRemoveNetworksForApp() throws Exception { 2697 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 2698 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 2699 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 2700 2701 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2702 2703 ApplicationInfo app = new ApplicationInfo(); 2704 app.uid = TEST_CREATOR_UID; 2705 app.packageName = TEST_CREATOR_NAME; 2706 assertEquals(3, mWifiConfigManager.removeNetworksForApp(app).size()); 2707 2708 // Ensure all the networks are removed now. 2709 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2710 } 2711 2712 /** 2713 * Verifies that all the networks for the provided user is removed when 2714 * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked. 2715 */ 2716 @Test 2717 public void testRemoveNetworksForUser() throws Exception { 2718 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 2719 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 2720 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 2721 2722 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2723 2724 assertEquals(3, mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER).size()); 2725 2726 // Ensure all the networks are removed now. 2727 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2728 } 2729 2730 /** 2731 * Verifies that the connect choice is removed from all networks when 2732 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked. 2733 */ 2734 @Test 2735 public void testRemoveNetworkRemovesConnectChoice() throws Exception { 2736 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 2737 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 2738 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 2739 verifyAddNetworkToWifiConfigManager(network1); 2740 verifyAddNetworkToWifiConfigManager(network2); 2741 verifyAddNetworkToWifiConfigManager(network3); 2742 2743 // Set connect choice of network 2 over network 1. 2744 assertTrue( 2745 mWifiConfigManager.setNetworkConnectChoice( 2746 network1.networkId, network2.configKey(), 78L)); 2747 2748 WifiConfiguration retrievedNetwork = 2749 mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2750 assertEquals( 2751 network2.configKey(), 2752 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2753 2754 // Remove network 3 and ensure that the connect choice on network 1 is not removed. 2755 assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID)); 2756 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2757 assertEquals( 2758 network2.configKey(), 2759 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2760 2761 // Now remove network 2 and ensure that the connect choice on network 1 is removed.. 2762 assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID)); 2763 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2764 assertNotEquals( 2765 network2.configKey(), 2766 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2767 2768 // This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for 2769 // clearing it after network removal. 2770 mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(eq(false)); 2771 } 2772 2773 /** 2774 * Verifies that all the ephemeral and passpoint networks are removed when 2775 * {@link WifiConfigManager#removeAllEphemeralOrPasspointConfiguredNetworks()} is invoked. 2776 */ 2777 @Test 2778 public void testRemoveAllEphemeralOrPasspointConfiguredNetworks() throws Exception { 2779 WifiConfiguration savedOpenNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 2780 WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createEphemeralNetwork(); 2781 WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork(); 2782 2783 verifyAddNetworkToWifiConfigManager(savedOpenNetwork); 2784 verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork); 2785 verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork); 2786 2787 List<WifiConfiguration> expectedConfigsBeforeRemove = new ArrayList<WifiConfiguration>() {{ 2788 add(savedOpenNetwork); 2789 add(ephemeralNetwork); 2790 add(passpointNetwork); 2791 }}; 2792 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2793 expectedConfigsBeforeRemove, mWifiConfigManager.getConfiguredNetworks()); 2794 2795 assertTrue(mWifiConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks()); 2796 2797 List<WifiConfiguration> expectedConfigsAfterRemove = new ArrayList<WifiConfiguration>() {{ 2798 add(savedOpenNetwork); 2799 }}; 2800 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2801 expectedConfigsAfterRemove, mWifiConfigManager.getConfiguredNetworks()); 2802 2803 // No more ephemeral or passpoint networks to remove now. 2804 assertFalse(mWifiConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks()); 2805 } 2806 2807 /** 2808 * Verifies that the modification of a single network using 2809 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any 2810 * updates to the network config in 2811 * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected 2812 * in the internal database. 2813 */ 2814 @Test 2815 public void testUpdateSingleNetworkWithKeysUpdate() { 2816 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 2817 network.enterpriseConfig = 2818 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 2819 verifyAddNetworkToWifiConfigManager(network); 2820 2821 // Now verify that network configurations match before we make any change. 2822 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2823 network, 2824 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2825 2826 // Modify the network ca_cert field in updateNetworkKeys method during a network 2827 // config update. 2828 final String newCaCertAlias = "test"; 2829 assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias()); 2830 2831 doAnswer(new AnswerWithArguments() { 2832 public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) { 2833 newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2834 return true; 2835 } 2836 }).when(mWifiKeyStore).updateNetworkKeys( 2837 any(WifiConfiguration.class), any(WifiConfiguration.class)); 2838 2839 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 2840 2841 // Now verify that the keys update is reflected in the configuration fetched from internal 2842 // db. 2843 network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2844 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2845 network, 2846 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2847 } 2848 2849 /** 2850 * Verifies that the dump method prints out all the saved network details with passwords masked. 2851 * {@link WifiConfigManager#dump(FileDescriptor, PrintWriter, String[])}. 2852 */ 2853 @Test 2854 public void testDump() { 2855 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2856 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 2857 eapNetwork.enterpriseConfig.setPassword("blah"); 2858 2859 verifyAddNetworkToWifiConfigManager(pskNetwork); 2860 verifyAddNetworkToWifiConfigManager(eapNetwork); 2861 2862 StringWriter stringWriter = new StringWriter(); 2863 mWifiConfigManager.dump( 2864 new FileDescriptor(), new PrintWriter(stringWriter), new String[0]); 2865 String dumpString = stringWriter.toString(); 2866 2867 // Ensure that the network SSIDs were dumped out. 2868 assertTrue(dumpString.contains(pskNetwork.SSID)); 2869 assertTrue(dumpString.contains(eapNetwork.SSID)); 2870 2871 // Ensure that the network passwords were not dumped out. 2872 assertFalse(dumpString.contains(pskNetwork.preSharedKey)); 2873 assertFalse(dumpString.contains(eapNetwork.enterpriseConfig.getPassword())); 2874 } 2875 2876 /** 2877 * Verifies the ordering of network list generated using 2878 * {@link WifiConfigManager#retrieveHiddenNetworkList()}. 2879 */ 2880 @Test 2881 public void testRetrieveHiddenList() { 2882 // Create and add 3 networks. 2883 WifiConfiguration network1 = WifiConfigurationTestUtil.createWepHiddenNetwork(); 2884 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskHiddenNetwork(); 2885 WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2886 verifyAddNetworkToWifiConfigManager(network1); 2887 verifyAddNetworkToWifiConfigManager(network2); 2888 verifyAddNetworkToWifiConfigManager(network3); 2889 2890 // Enable all of them. 2891 assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID)); 2892 assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID)); 2893 assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID)); 2894 2895 // Now set scan results in 2 of them to set the corresponding 2896 // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field. 2897 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 2898 network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54)); 2899 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 2900 network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54)); 2901 2902 // Now increment |network3|'s association count. This should ensure that this network 2903 // is preferred over |network1|. 2904 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId)); 2905 2906 // Retrieve the hidden network list & verify the order of the networks returned. 2907 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = 2908 mWifiConfigManager.retrieveHiddenNetworkList(); 2909 assertEquals(3, hiddenNetworks.size()); 2910 assertEquals(network3.SSID, hiddenNetworks.get(0).ssid); 2911 assertEquals(network1.SSID, hiddenNetworks.get(1).ssid); 2912 assertEquals(network2.SSID, hiddenNetworks.get(2).ssid); 2913 2914 // Now permanently disable |network3|. This should remove network 3 from the list. 2915 assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID)); 2916 2917 // Retrieve the hidden network list again & verify the order of the networks returned. 2918 hiddenNetworks = mWifiConfigManager.retrieveHiddenNetworkList(); 2919 assertEquals(2, hiddenNetworks.size()); 2920 assertEquals(network1.SSID, hiddenNetworks.get(0).ssid); 2921 assertEquals(network2.SSID, hiddenNetworks.get(1).ssid); 2922 } 2923 2924 /** 2925 * Verifies the addition of network configurations using 2926 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and 2927 * default key mgmt does not add duplicate network configs. 2928 */ 2929 @Test 2930 public void testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt() { 2931 final String ssid = "\"test_blah\""; 2932 // Add a network with the above SSID and default key mgmt and ensure it was added 2933 // successfully. 2934 WifiConfiguration network1 = new WifiConfiguration(); 2935 network1.SSID = ssid; 2936 NetworkUpdateResult result = addNetworkToWifiConfigManager(network1); 2937 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2938 assertTrue(result.isNewNetwork()); 2939 2940 List<WifiConfiguration> retrievedNetworks = 2941 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2942 assertEquals(1, retrievedNetworks.size()); 2943 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2944 network1, retrievedNetworks.get(0)); 2945 2946 // Now add a second network with the same SSID and default key mgmt and ensure that it 2947 // didn't add a new duplicate network. 2948 WifiConfiguration network2 = new WifiConfiguration(); 2949 network2.SSID = ssid; 2950 result = addNetworkToWifiConfigManager(network2); 2951 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2952 assertFalse(result.isNewNetwork()); 2953 2954 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2955 assertEquals(1, retrievedNetworks.size()); 2956 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2957 network2, retrievedNetworks.get(0)); 2958 } 2959 2960 /** 2961 * Verifies the addition of network configurations using 2962 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and 2963 * different key mgmt should add different network configs. 2964 */ 2965 @Test 2966 public void testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt() { 2967 final String ssid = "\"test_blah\""; 2968 // Add a network with the above SSID and WPA_PSK key mgmt and ensure it was added 2969 // successfully. 2970 WifiConfiguration network1 = new WifiConfiguration(); 2971 network1.SSID = ssid; 2972 network1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 2973 network1.preSharedKey = "\"test_blah\""; 2974 NetworkUpdateResult result = addNetworkToWifiConfigManager(network1); 2975 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2976 assertTrue(result.isNewNetwork()); 2977 2978 List<WifiConfiguration> retrievedNetworks = 2979 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2980 assertEquals(1, retrievedNetworks.size()); 2981 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2982 network1, retrievedNetworks.get(0)); 2983 2984 // Now add a second network with the same SSID and NONE key mgmt and ensure that it 2985 // does add a new network. 2986 WifiConfiguration network2 = new WifiConfiguration(); 2987 network2.SSID = ssid; 2988 network2.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 2989 result = addNetworkToWifiConfigManager(network2); 2990 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2991 assertTrue(result.isNewNetwork()); 2992 2993 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2994 assertEquals(2, retrievedNetworks.size()); 2995 List<WifiConfiguration> networks = Arrays.asList(network1, network2); 2996 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2997 networks, retrievedNetworks); 2998 } 2999 3000 /** 3001 * Verifies that adding a network with a proxy, without having permission OVERRIDE_WIFI_CONFIG, 3002 * holding device policy, or profile owner policy fails. 3003 */ 3004 @Test 3005 public void testAddNetworkWithProxyFails() { 3006 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3007 false, // withNetworkSettings 3008 false, // withProfileOwnerPolicy 3009 false, // withDeviceOwnerPolicy 3010 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3011 false, // assertSuccess 3012 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3013 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3014 false, // withNetworkSettings 3015 false, // withProfileOwnerPolicy 3016 false, // withDeviceOwnerPolicy 3017 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3018 false, // assertSuccess 3019 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3020 } 3021 3022 /** 3023 * Verifies that adding a network with a PAC or STATIC proxy with permission 3024 * OVERRIDE_WIFI_CONFIG is successful 3025 */ 3026 @Test 3027 public void testAddNetworkWithProxyWithConfOverride() { 3028 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3029 true, // withNetworkSettings 3030 false, // withProfileOwnerPolicy 3031 false, // withDeviceOwnerPolicy 3032 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3033 true, // assertSuccess 3034 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3035 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3036 true, // withNetworkSettings 3037 false, // withProfileOwnerPolicy 3038 false, // withDeviceOwnerPolicy 3039 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3040 true, // assertSuccess 3041 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3042 } 3043 3044 /** 3045 * Verifies that adding a network with a PAC or STATIC proxy, while holding policy 3046 * {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER} is successful 3047 */ 3048 @Test 3049 public void testAddNetworkWithProxyAsProfileOwner() { 3050 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3051 false, // withNetworkSettings 3052 true, // withProfileOwnerPolicy 3053 false, // withDeviceOwnerPolicy 3054 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3055 true, // assertSuccess 3056 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3057 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3058 false, // withNetworkSettings 3059 true, // withProfileOwnerPolicy 3060 false, // withDeviceOwnerPolicy 3061 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3062 true, // assertSuccess 3063 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3064 } 3065 /** 3066 * Verifies that adding a network with a PAC or STATIC proxy, while holding policy 3067 * {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER} is successful 3068 */ 3069 @Test 3070 public void testAddNetworkWithProxyAsDeviceOwner() { 3071 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3072 false, // withNetworkSettings 3073 false, // withProfileOwnerPolicy 3074 true, // withDeviceOwnerPolicy 3075 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3076 true, // assertSuccess 3077 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3078 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3079 false, // withNetworkSettings 3080 false, // withProfileOwnerPolicy 3081 true, // withDeviceOwnerPolicy 3082 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3083 true, // assertSuccess 3084 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3085 } 3086 /** 3087 * Verifies that updating a network (that has no proxy) and adding a PAC or STATIC proxy fails 3088 * without being able to override configs, or holding Device or Profile owner policies. 3089 */ 3090 @Test 3091 public void testUpdateNetworkAddProxyFails() { 3092 WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3093 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 3094 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3095 false, // withNetworkSettings 3096 false, // withProfileOwnerPolicy 3097 false, // withDeviceOwnerPolicy 3098 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3099 false, // assertSuccess 3100 result.getNetworkId()); // Update networkID 3101 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3102 false, // withNetworkSettings 3103 false, // withProfileOwnerPolicy 3104 false, // withDeviceOwnerPolicy 3105 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 3106 false, // assertSuccess 3107 result.getNetworkId()); // Update networkID 3108 } 3109 /** 3110 * Verifies that updating a network and adding a proxy is successful in the cases where app can 3111 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3112 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3113 * otherwise. 3114 */ 3115 @Test 3116 public void testUpdateNetworkAddProxyWithPermissionAndSystem() { 3117 // Testing updating network with uid permission OVERRIDE_WIFI_CONFIG 3118 WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3119 NetworkUpdateResult result = addNetworkToWifiConfigManager(network, TEST_CREATOR_UID); 3120 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3121 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3122 true, // withNetworkSettings 3123 false, // withProfileOwnerPolicy 3124 false, // withDeviceOwnerPolicy 3125 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3126 true, // assertSuccess 3127 result.getNetworkId()); // Update networkID 3128 3129 // Testing updating network with proxy while holding Profile Owner policy 3130 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3131 result = addNetworkToWifiConfigManager(network, TEST_NO_PERM_UID); 3132 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3133 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3134 false, // withNetworkSettings 3135 true, // withProfileOwnerPolicy 3136 false, // withDeviceOwnerPolicy 3137 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3138 true, // assertSuccess 3139 result.getNetworkId()); // Update networkID 3140 3141 // Testing updating network with proxy while holding Device Owner Policy 3142 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3143 result = addNetworkToWifiConfigManager(network, TEST_NO_PERM_UID); 3144 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3145 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3146 false, // withNetworkSettings 3147 false, // withProfileOwnerPolicy 3148 true, // withDeviceOwnerPolicy 3149 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 3150 true, // assertSuccess 3151 result.getNetworkId()); // Update networkID 3152 } 3153 3154 /** 3155 * Verifies that updating a network that has a proxy without changing the proxy, can succeed 3156 * without proxy specific permissions. 3157 */ 3158 @Test 3159 public void testUpdateNetworkUnchangedProxy() { 3160 IpConfiguration ipConf = WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(); 3161 // First create a WifiConfiguration with proxy 3162 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3163 false, // withNetworkSettings 3164 true, // withProfileOwnerPolicy 3165 false, // withDeviceOwnerPolicy 3166 ipConf, 3167 true, // assertSuccess 3168 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3169 // Update the network while using the same ipConf, and no proxy specific permissions 3170 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3171 false, // withNetworkSettings 3172 false, // withProfileOwnerPolicy 3173 false, // withDeviceOwnerPolicy 3174 ipConf, 3175 true, // assertSuccess 3176 result.getNetworkId()); // Update networkID 3177 } 3178 3179 /** 3180 * Verifies that updating a network with a different proxy succeeds in the cases where app can 3181 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3182 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3183 * otherwise. 3184 */ 3185 @Test 3186 public void testUpdateNetworkDifferentProxy() { 3187 // Create two proxy configurations of the same type, but different values 3188 IpConfiguration ipConf1 = 3189 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3190 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3191 TEST_STATIC_PROXY_HOST_1, 3192 TEST_STATIC_PROXY_PORT_1, 3193 TEST_STATIC_PROXY_EXCLUSION_LIST_1, 3194 TEST_PAC_PROXY_LOCATION_1); 3195 IpConfiguration ipConf2 = 3196 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3197 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3198 TEST_STATIC_PROXY_HOST_2, 3199 TEST_STATIC_PROXY_PORT_2, 3200 TEST_STATIC_PROXY_EXCLUSION_LIST_2, 3201 TEST_PAC_PROXY_LOCATION_2); 3202 3203 // Update with Conf Override 3204 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3205 true, // withNetworkSettings 3206 false, // withProfileOwnerPolicy 3207 false, // withDeviceOwnerPolicy 3208 ipConf1, 3209 true, // assertSuccess 3210 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3211 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3212 true, // withNetworkSettings 3213 false, // withProfileOwnerPolicy 3214 false, // withDeviceOwnerPolicy 3215 ipConf2, 3216 true, // assertSuccess 3217 result.getNetworkId()); // Update networkID 3218 3219 // Update as Device Owner 3220 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3221 false, // withNetworkSettings 3222 false, // withProfileOwnerPolicy 3223 true, // withDeviceOwnerPolicy 3224 ipConf1, 3225 true, // assertSuccess 3226 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3227 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3228 false, // withNetworkSettings 3229 false, // withProfileOwnerPolicy 3230 true, // withDeviceOwnerPolicy 3231 ipConf2, 3232 true, // assertSuccess 3233 result.getNetworkId()); // Update networkID 3234 3235 // Update as Profile Owner 3236 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3237 false, // withNetworkSettings 3238 true, // withProfileOwnerPolicy 3239 false, // withDeviceOwnerPolicy 3240 ipConf1, 3241 true, // assertSuccess 3242 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3243 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3244 false, // withNetworkSettings 3245 true, // withProfileOwnerPolicy 3246 false, // withDeviceOwnerPolicy 3247 ipConf2, 3248 true, // assertSuccess 3249 result.getNetworkId()); // Update networkID 3250 3251 // Update with no permissions (should fail) 3252 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3253 false, // withNetworkSettings 3254 true, // withProfileOwnerPolicy 3255 false, // withDeviceOwnerPolicy 3256 ipConf1, 3257 true, // assertSuccess 3258 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3259 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3260 false, // withNetworkSettings 3261 false, // withProfileOwnerPolicy 3262 false, // withDeviceOwnerPolicy 3263 ipConf2, 3264 false, // assertSuccess 3265 result.getNetworkId()); // Update networkID 3266 } 3267 /** 3268 * Verifies that updating a network removing its proxy succeeds in the cases where app can 3269 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3270 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3271 * otherwise. 3272 */ 3273 @Test 3274 public void testUpdateNetworkRemoveProxy() { 3275 // Create two different IP configurations, one with a proxy and another without. 3276 IpConfiguration ipConf1 = 3277 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3278 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3279 TEST_STATIC_PROXY_HOST_1, 3280 TEST_STATIC_PROXY_PORT_1, 3281 TEST_STATIC_PROXY_EXCLUSION_LIST_1, 3282 TEST_PAC_PROXY_LOCATION_1); 3283 IpConfiguration ipConf2 = 3284 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3285 WifiConfigurationTestUtil.NONE_PROXY_SETTING, 3286 TEST_STATIC_PROXY_HOST_2, 3287 TEST_STATIC_PROXY_PORT_2, 3288 TEST_STATIC_PROXY_EXCLUSION_LIST_2, 3289 TEST_PAC_PROXY_LOCATION_2); 3290 3291 // Update with Conf Override 3292 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3293 true, // withNetworkSettings 3294 false, // withProfileOwnerPolicy 3295 false, // withDeviceOwnerPolicy 3296 ipConf1, 3297 true, // assertSuccess 3298 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3299 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3300 true, // withNetworkSettings 3301 false, // withProfileOwnerPolicy 3302 false, // withDeviceOwnerPolicy 3303 ipConf2, 3304 true, // assertSuccess 3305 result.getNetworkId()); // Update networkID 3306 3307 // Update as Device Owner 3308 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3309 false, // withNetworkSettings 3310 false, // withProfileOwnerPolicy 3311 true, // withDeviceOwnerPolicy 3312 ipConf1, 3313 true, // assertSuccess 3314 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3315 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3316 false, // withNetworkSettings 3317 false, // withProfileOwnerPolicy 3318 true, // withDeviceOwnerPolicy 3319 ipConf2, 3320 true, // assertSuccess 3321 result.getNetworkId()); // Update networkID 3322 3323 // Update as Profile Owner 3324 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3325 false, // withNetworkSettings 3326 true, // withProfileOwnerPolicy 3327 false, // withDeviceOwnerPolicy 3328 ipConf1, 3329 true, // assertSuccess 3330 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3331 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3332 false, // withNetworkSettings 3333 true, // withProfileOwnerPolicy 3334 false, // withDeviceOwnerPolicy 3335 ipConf2, 3336 true, // assertSuccess 3337 result.getNetworkId()); // Update networkID 3338 3339 // Update with no permissions (should fail) 3340 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3341 false, // withNetworkSettings 3342 true, // withProfileOwnerPolicy 3343 false, // withDeviceOwnerPolicy 3344 ipConf1, 3345 true, // assertSuccess 3346 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3347 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3348 false, // withNetworkSettings 3349 false, // withProfileOwnerPolicy 3350 false, // withDeviceOwnerPolicy 3351 ipConf2, 3352 false, // assertSuccess 3353 result.getNetworkId()); // Update networkID 3354 } 3355 3356 /** 3357 * Verifies that the app specified BSSID is converted and saved in lower case. 3358 */ 3359 @Test 3360 public void testAppSpecifiedBssidIsSavedInLowerCase() { 3361 final String bssid = "0A:08:5C:BB:89:6D"; // upper case 3362 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 3363 openNetwork.BSSID = bssid; 3364 3365 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 3366 3367 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork( 3368 result.getNetworkId()); 3369 3370 assertNotEquals(retrievedNetwork.BSSID, bssid); 3371 assertEquals(retrievedNetwork.BSSID, bssid.toLowerCase()); 3372 } 3373 3374 private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3375 boolean withNetworkSettings, 3376 boolean withProfileOwnerPolicy, 3377 boolean withDeviceOwnerPolicy, 3378 IpConfiguration ipConfiguration, 3379 boolean assertSuccess, 3380 int networkId) { 3381 WifiConfiguration network; 3382 if (networkId == WifiConfiguration.INVALID_NETWORK_ID) { 3383 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3384 } else { 3385 network = mWifiConfigManager.getConfiguredNetwork(networkId); 3386 } 3387 network.setIpConfiguration(ipConfiguration); 3388 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 3389 eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))) 3390 .thenReturn(withProfileOwnerPolicy); 3391 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 3392 eq(DeviceAdminInfo.USES_POLICY_DEVICE_OWNER))) 3393 .thenReturn(withDeviceOwnerPolicy); 3394 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())) 3395 .thenReturn(withNetworkSettings); 3396 int uid = withNetworkSettings ? TEST_CREATOR_UID : TEST_NO_PERM_UID; 3397 NetworkUpdateResult result = addNetworkToWifiConfigManager(network, uid); 3398 assertEquals(assertSuccess, result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3399 return result; 3400 } 3401 3402 private void createWifiConfigManager() { 3403 mWifiConfigManager = 3404 new WifiConfigManager( 3405 mContext, mClock, mUserManager, mTelephonyManager, 3406 mWifiKeyStore, mWifiConfigStore, 3407 mWifiPermissionsUtil, mWifiPermissionsWrapper, mNetworkListStoreData, 3408 mDeletedEphemeralSsidsStoreData); 3409 mWifiConfigManager.enableVerboseLogging(1); 3410 } 3411 3412 /** 3413 * This method sets defaults in the provided WifiConfiguration object if not set 3414 * so that it can be used for comparison with the configuration retrieved from 3415 * WifiConfigManager. 3416 */ 3417 private void setDefaults(WifiConfiguration configuration) { 3418 if (configuration.allowedAuthAlgorithms.isEmpty()) { 3419 configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 3420 } 3421 if (configuration.allowedProtocols.isEmpty()) { 3422 configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 3423 configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 3424 } 3425 if (configuration.allowedKeyManagement.isEmpty()) { 3426 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 3427 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); 3428 } 3429 if (configuration.allowedPairwiseCiphers.isEmpty()) { 3430 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 3431 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 3432 } 3433 if (configuration.allowedGroupCiphers.isEmpty()) { 3434 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 3435 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 3436 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 3437 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); 3438 } 3439 if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) { 3440 configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP); 3441 } 3442 if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) { 3443 configuration.setProxySettings(IpConfiguration.ProxySettings.NONE); 3444 } 3445 configuration.status = WifiConfiguration.Status.DISABLED; 3446 configuration.getNetworkSelectionStatus().setNetworkSelectionStatus( 3447 NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED); 3448 } 3449 3450 /** 3451 * Modifies the provided configuration with creator uid, package name 3452 * and time. 3453 */ 3454 private void setCreationDebugParams(WifiConfiguration configuration) { 3455 configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID; 3456 configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME; 3457 configuration.creationTime = configuration.updateTime = 3458 WifiConfigManager.createDebugTimeStampString( 3459 TEST_WALLCLOCK_CREATION_TIME_MILLIS); 3460 } 3461 3462 /** 3463 * Modifies the provided configuration with update uid, package name 3464 * and time. 3465 */ 3466 private void setUpdateDebugParams(WifiConfiguration configuration) { 3467 configuration.lastUpdateUid = TEST_UPDATE_UID; 3468 configuration.lastUpdateName = TEST_UPDATE_NAME; 3469 configuration.updateTime = 3470 WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 3471 } 3472 3473 private void assertNotEquals(Object expected, Object actual) { 3474 if (actual != null) { 3475 assertFalse(actual.equals(expected)); 3476 } else { 3477 assertNotNull(expected); 3478 } 3479 } 3480 3481 /** 3482 * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that 3483 * the existing |BSSID| field is not the same value as the one being set 3484 */ 3485 private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) { 3486 assertNotEquals(bssid, configuration.BSSID); 3487 configuration.BSSID = bssid; 3488 } 3489 3490 /** 3491 * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also, 3492 * asserts that the existing |mIpConfiguration| field is not the same value as the one being set 3493 */ 3494 private void assertAndSetNetworkIpConfiguration( 3495 WifiConfiguration configuration, IpConfiguration ipConfiguration) { 3496 assertNotEquals(ipConfiguration, configuration.getIpConfiguration()); 3497 configuration.setIpConfiguration(ipConfiguration); 3498 } 3499 3500 /** 3501 * Modifies the provided WifiConfiguration with the specified |wepKeys| value and 3502 * |wepTxKeyIndex|. 3503 */ 3504 private void assertAndSetNetworkWepKeysAndTxIndex( 3505 WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) { 3506 assertNotEquals(wepKeys, configuration.wepKeys); 3507 assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex); 3508 configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length); 3509 configuration.wepTxKeyIndex = wepTxKeyIdx; 3510 } 3511 3512 /** 3513 * Modifies the provided WifiConfiguration with the specified |preSharedKey| value. 3514 */ 3515 private void assertAndSetNetworkPreSharedKey( 3516 WifiConfiguration configuration, String preSharedKey) { 3517 assertNotEquals(preSharedKey, configuration.preSharedKey); 3518 configuration.preSharedKey = preSharedKey; 3519 } 3520 3521 /** 3522 * Modifies the provided WifiConfiguration with the specified enteprise |password| value. 3523 */ 3524 private void assertAndSetNetworkEnterprisePassword( 3525 WifiConfiguration configuration, String password) { 3526 assertNotEquals(password, configuration.enterpriseConfig.getPassword()); 3527 configuration.enterpriseConfig.setPassword(password); 3528 } 3529 3530 /** 3531 * Helper method to capture the networks list store data that will be written by 3532 * WifiConfigStore.write() method. 3533 */ 3534 private Pair<List<WifiConfiguration>, List<WifiConfiguration>> 3535 captureWriteNetworksListStoreData() { 3536 try { 3537 ArgumentCaptor<ArrayList> sharedConfigsCaptor = 3538 ArgumentCaptor.forClass(ArrayList.class); 3539 ArgumentCaptor<ArrayList> userConfigsCaptor = 3540 ArgumentCaptor.forClass(ArrayList.class); 3541 mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData) 3542 .setSharedConfigurations(sharedConfigsCaptor.capture()); 3543 mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData) 3544 .setUserConfigurations(userConfigsCaptor.capture()); 3545 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 3546 return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue()); 3547 } catch (Exception e) { 3548 fail("Exception encountered during write " + e); 3549 } 3550 return null; 3551 } 3552 3553 /** 3554 * Returns whether the provided network was in the store data or not. 3555 */ 3556 private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) { 3557 Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData = 3558 captureWriteNetworksListStoreData(); 3559 if (networkListStoreData == null) { 3560 return false; 3561 } 3562 List<WifiConfiguration> networkList = new ArrayList<>(); 3563 networkList.addAll(networkListStoreData.first); 3564 networkList.addAll(networkListStoreData.second); 3565 return isNetworkInConfigStoreData(configuration, networkList); 3566 } 3567 3568 /** 3569 * Returns whether the provided network was in the store data or not. 3570 */ 3571 private boolean isNetworkInConfigStoreData( 3572 WifiConfiguration configuration, List<WifiConfiguration> networkList) { 3573 boolean foundNetworkInStoreData = false; 3574 for (WifiConfiguration retrievedConfig : networkList) { 3575 if (retrievedConfig.configKey().equals(configuration.configKey())) { 3576 foundNetworkInStoreData = true; 3577 break; 3578 } 3579 } 3580 return foundNetworkInStoreData; 3581 } 3582 3583 /** 3584 * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData 3585 * after WifiConfigStore#read. 3586 */ 3587 private void setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations, 3588 List<WifiConfiguration> userConfigurations, Set<String> deletedEphemeralSsids) { 3589 when(mNetworkListStoreData.getSharedConfigurations()) 3590 .thenReturn(sharedConfigurations); 3591 when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations); 3592 when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids); 3593 } 3594 3595 /** 3596 * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData 3597 * after WifiConfigStore#switchUserStoreAndRead. 3598 */ 3599 private void setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations, 3600 Set<String> deletedEphemeralSsids) { 3601 when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations); 3602 when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids); 3603 } 3604 3605 /** 3606 * Verifies that the provided network was not present in the last config store write. 3607 */ 3608 private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) { 3609 assertFalse(isNetworkInConfigStoreData(configuration)); 3610 } 3611 3612 /** 3613 * Verifies that the provided network was present in the last config store write. 3614 */ 3615 private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) { 3616 assertTrue(isNetworkInConfigStoreData(configuration)); 3617 } 3618 3619 private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) { 3620 if (!TextUtils.isEmpty(configuration.preSharedKey)) { 3621 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey); 3622 } 3623 if (configuration.wepKeys != null) { 3624 for (int i = 0; i < configuration.wepKeys.length; i++) { 3625 if (!TextUtils.isEmpty(configuration.wepKeys[i])) { 3626 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]); 3627 } 3628 } 3629 } 3630 if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) { 3631 assertEquals( 3632 WifiConfigManager.PASSWORD_MASK, 3633 configuration.enterpriseConfig.getPassword()); 3634 } 3635 } 3636 3637 /** 3638 * Verifies that the network was present in the network change broadcast and returns the 3639 * change reason. 3640 */ 3641 private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) { 3642 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 3643 ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class); 3644 mContextConfigStoreMockOrder.verify(mContext) 3645 .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture()); 3646 3647 assertEquals(userHandleCaptor.getValue(), UserHandle.ALL); 3648 Intent intent = intentCaptor.getValue(); 3649 3650 int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1); 3651 WifiConfiguration retrievedConfig = 3652 (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION); 3653 assertEquals(retrievedConfig.configKey(), configuration.configKey()); 3654 3655 // Verify that all the passwords are masked in the broadcast configuration. 3656 assertPasswordsMaskedInWifiConfiguration(retrievedConfig); 3657 3658 return changeReason; 3659 } 3660 3661 /** 3662 * Verifies that we sent out an add broadcast with the provided network. 3663 */ 3664 private void verifyNetworkAddBroadcast(WifiConfiguration configuration) { 3665 assertEquals( 3666 verifyNetworkInBroadcastAndReturnReason(configuration), 3667 WifiManager.CHANGE_REASON_ADDED); 3668 } 3669 3670 /** 3671 * Verifies that we sent out an update broadcast with the provided network. 3672 */ 3673 private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) { 3674 assertEquals( 3675 verifyNetworkInBroadcastAndReturnReason(configuration), 3676 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 3677 } 3678 3679 /** 3680 * Verifies that we sent out a remove broadcast with the provided network. 3681 */ 3682 private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) { 3683 assertEquals( 3684 verifyNetworkInBroadcastAndReturnReason(configuration), 3685 WifiManager.CHANGE_REASON_REMOVED); 3686 } 3687 3688 private void verifyWifiConfigStoreRead() { 3689 assertTrue(mWifiConfigManager.loadFromStore()); 3690 mContextConfigStoreMockOrder.verify(mContext) 3691 .sendBroadcastAsUser(any(Intent.class), any(UserHandle.class)); 3692 } 3693 3694 private void triggerStoreReadIfNeeded() { 3695 // Trigger a store read if not already done. 3696 if (!mStoreReadTriggered) { 3697 verifyWifiConfigStoreRead(); 3698 mStoreReadTriggered = true; 3699 } 3700 } 3701 3702 /** 3703 * Adds the provided configuration to WifiConfigManager with uid = TEST_CREATOR_UID. 3704 */ 3705 private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) { 3706 return addNetworkToWifiConfigManager(configuration, TEST_CREATOR_UID); 3707 } 3708 3709 /** 3710 * Adds the provided configuration to WifiConfigManager and modifies the provided configuration 3711 * with creator/update uid, package name and time. This also sets defaults for fields not 3712 * populated. 3713 * These fields are populated internally by WifiConfigManager and hence we need 3714 * to modify the configuration before we compare the added network with the retrieved network. 3715 * This method also triggers a store read if not already done. 3716 */ 3717 private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration, 3718 int uid) { 3719 clearInvocations(mContext, mWifiConfigStore, mNetworkListStoreData); 3720 triggerStoreReadIfNeeded(); 3721 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS); 3722 NetworkUpdateResult result = 3723 mWifiConfigManager.addOrUpdateNetwork(configuration, uid); 3724 setDefaults(configuration); 3725 setCreationDebugParams(configuration); 3726 configuration.networkId = result.getNetworkId(); 3727 return result; 3728 } 3729 3730 /** 3731 * Add network to WifiConfigManager and ensure that it was successful. 3732 */ 3733 private NetworkUpdateResult verifyAddNetworkToWifiConfigManager( 3734 WifiConfiguration configuration) { 3735 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3736 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3737 assertTrue(result.isNewNetwork()); 3738 assertTrue(result.hasIpChanged()); 3739 assertTrue(result.hasProxyChanged()); 3740 3741 verifyNetworkAddBroadcast(configuration); 3742 // Verify that the config store write was triggered with this new configuration. 3743 verifyNetworkInConfigStoreData(configuration); 3744 return result; 3745 } 3746 3747 /** 3748 * Add ephemeral network to WifiConfigManager and ensure that it was successful. 3749 */ 3750 private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager( 3751 WifiConfiguration configuration) throws Exception { 3752 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3753 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3754 assertTrue(result.isNewNetwork()); 3755 assertTrue(result.hasIpChanged()); 3756 assertTrue(result.hasProxyChanged()); 3757 3758 verifyNetworkAddBroadcast(configuration); 3759 // Ensure that the write was not invoked for ephemeral network addition. 3760 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3761 return result; 3762 } 3763 3764 /** 3765 * Add Passpoint network to WifiConfigManager and ensure that it was successful. 3766 */ 3767 private NetworkUpdateResult verifyAddPasspointNetworkToWifiConfigManager( 3768 WifiConfiguration configuration) throws Exception { 3769 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3770 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3771 assertTrue(result.isNewNetwork()); 3772 assertTrue(result.hasIpChanged()); 3773 assertTrue(result.hasProxyChanged()); 3774 3775 // Verify keys are not being installed. 3776 verify(mWifiKeyStore, never()).updateNetworkKeys(any(WifiConfiguration.class), 3777 any(WifiConfiguration.class)); 3778 verifyNetworkAddBroadcast(configuration); 3779 // Ensure that the write was not invoked for Passpoint network addition. 3780 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3781 return result; 3782 } 3783 3784 /** 3785 * Updates the provided configuration to WifiConfigManager and modifies the provided 3786 * configuration with update uid, package name and time. 3787 * These fields are populated internally by WifiConfigManager and hence we need 3788 * to modify the configuration before we compare the added network with the retrieved network. 3789 */ 3790 private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) { 3791 clearInvocations(mContext, mWifiConfigStore, mNetworkListStoreData); 3792 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 3793 NetworkUpdateResult result = 3794 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID); 3795 setUpdateDebugParams(configuration); 3796 return result; 3797 } 3798 3799 /** 3800 * Update network to WifiConfigManager config change and ensure that it was successful. 3801 */ 3802 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager( 3803 WifiConfiguration configuration) { 3804 NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration); 3805 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3806 assertFalse(result.isNewNetwork()); 3807 3808 verifyNetworkUpdateBroadcast(configuration); 3809 // Verify that the config store write was triggered with this new configuration. 3810 verifyNetworkInConfigStoreData(configuration); 3811 return result; 3812 } 3813 3814 /** 3815 * Update network to WifiConfigManager without IP config change and ensure that it was 3816 * successful. 3817 */ 3818 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange( 3819 WifiConfiguration configuration) { 3820 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 3821 assertFalse(result.hasIpChanged()); 3822 assertFalse(result.hasProxyChanged()); 3823 return result; 3824 } 3825 3826 /** 3827 * Update network to WifiConfigManager with IP config change and ensure that it was 3828 * successful. 3829 */ 3830 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange( 3831 WifiConfiguration configuration) { 3832 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 3833 assertTrue(result.hasIpChanged()); 3834 assertTrue(result.hasProxyChanged()); 3835 return result; 3836 } 3837 3838 /** 3839 * Removes network from WifiConfigManager and ensure that it was successful. 3840 */ 3841 private void verifyRemoveNetworkFromWifiConfigManager( 3842 WifiConfiguration configuration) { 3843 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3844 3845 verifyNetworkRemoveBroadcast(configuration); 3846 // Verify if the config store write was triggered without this new configuration. 3847 verifyNetworkNotInConfigStoreData(configuration); 3848 } 3849 3850 /** 3851 * Removes ephemeral network from WifiConfigManager and ensure that it was successful. 3852 */ 3853 private void verifyRemoveEphemeralNetworkFromWifiConfigManager( 3854 WifiConfiguration configuration) throws Exception { 3855 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3856 3857 verifyNetworkRemoveBroadcast(configuration); 3858 // Ensure that the write was not invoked for ephemeral network remove. 3859 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3860 } 3861 3862 /** 3863 * Removes Passpoint network from WifiConfigManager and ensure that it was successful. 3864 */ 3865 private void verifyRemovePasspointNetworkFromWifiConfigManager( 3866 WifiConfiguration configuration) throws Exception { 3867 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3868 3869 // Verify keys are not being removed. 3870 verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class)); 3871 verifyNetworkRemoveBroadcast(configuration); 3872 // Ensure that the write was not invoked for Passpoint network remove. 3873 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3874 } 3875 3876 /** 3877 * Verifies the provided network's public status and ensures that the network change broadcast 3878 * has been sent out. 3879 */ 3880 private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) { 3881 assertEquals(status, configuration.status); 3882 verifyNetworkUpdateBroadcast(configuration); 3883 } 3884 3885 /** 3886 * Verifies the network's selection status update. 3887 * 3888 * For temporarily disabled reasons, the method ensures that the status has changed only if 3889 * disable reason counter has exceeded the threshold. 3890 * 3891 * For permanently disabled/enabled reasons, the method ensures that the public status has 3892 * changed and the network change broadcast has been sent out. 3893 */ 3894 private void verifyUpdateNetworkSelectionStatus( 3895 int networkId, int reason, int temporaryDisableReasonCounter) { 3896 when(mClock.getElapsedSinceBootMillis()) 3897 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS); 3898 3899 // Fetch the current status of the network before we try to update the status. 3900 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3901 NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus(); 3902 int currentDisableReason = currentStatus.getNetworkSelectionDisableReason(); 3903 3904 // First set the status to the provided reason. 3905 assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason)); 3906 3907 // Now fetch the network configuration and verify the new status of the network. 3908 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3909 3910 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 3911 int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason(); 3912 long retrievedDisableTime = retrievedStatus.getDisableTime(); 3913 int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason); 3914 int disableReasonThreshold = 3915 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason]; 3916 3917 if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) { 3918 assertEquals(reason, retrievedDisableReason); 3919 assertTrue(retrievedStatus.isNetworkEnabled()); 3920 assertEquals( 3921 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 3922 retrievedDisableTime); 3923 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 3924 } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) { 3925 // For temporarily disabled networks, we need to ensure that the current status remains 3926 // until the threshold is crossed. 3927 assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter); 3928 if (retrievedDisableReasonCounter < disableReasonThreshold) { 3929 assertEquals(currentDisableReason, retrievedDisableReason); 3930 assertEquals( 3931 currentStatus.getNetworkSelectionStatus(), 3932 retrievedStatus.getNetworkSelectionStatus()); 3933 } else { 3934 assertEquals(reason, retrievedDisableReason); 3935 assertTrue(retrievedStatus.isNetworkTemporaryDisabled()); 3936 assertEquals( 3937 TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime); 3938 } 3939 } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) { 3940 assertEquals(reason, retrievedDisableReason); 3941 assertTrue(retrievedStatus.isNetworkPermanentlyDisabled()); 3942 assertEquals( 3943 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 3944 retrievedDisableTime); 3945 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED); 3946 } 3947 } 3948 3949 /** 3950 * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency 3951 * values. 3952 */ 3953 private ScanDetail createScanDetailForNetwork( 3954 WifiConfiguration configuration, String bssid, int level, int frequency) { 3955 return WifiConfigurationTestUtil.createScanDetailForNetwork(configuration, bssid, level, 3956 frequency, mClock.getUptimeSinceBootMillis(), mClock.getWallClockMillis()); 3957 } 3958 /** 3959 * Creates a scan detail corresponding to the provided network and BSSID value. 3960 */ 3961 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) { 3962 return createScanDetailForNetwork(configuration, bssid, 0, 0); 3963 } 3964 3965 /** 3966 * Creates a scan detail corresponding to the provided network and fixed BSSID value. 3967 */ 3968 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) { 3969 return createScanDetailForNetwork(configuration, TEST_BSSID); 3970 } 3971 3972 /** 3973 * Adds the provided network and then creates a scan detail corresponding to the network. The 3974 * method then creates a ScanDetail corresponding to the network and ensures that the network 3975 * is properly matched using 3976 * {@link WifiConfigManager#getConfiguredNetworkForScanDetailAndCache(ScanDetail)} and also 3977 * verifies that the provided scan detail was cached, 3978 */ 3979 private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 3980 WifiConfiguration network) { 3981 // First add the provided network. 3982 verifyAddNetworkToWifiConfigManager(network); 3983 3984 // Now create a dummy scan detail corresponding to the network. 3985 ScanDetail scanDetail = createScanDetailForNetwork(network); 3986 ScanResult scanResult = scanDetail.getScanResult(); 3987 3988 WifiConfiguration retrievedNetwork = 3989 mWifiConfigManager.getConfiguredNetworkForScanDetailAndCache(scanDetail); 3990 // Retrieve the network with password data for comparison. 3991 retrievedNetwork = 3992 mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId); 3993 3994 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 3995 network, retrievedNetwork); 3996 3997 // Now retrieve the scan detail cache and ensure that the new scan detail is in cache. 3998 ScanDetailCache retrievedScanDetailCache = 3999 mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId); 4000 assertEquals(1, retrievedScanDetailCache.size()); 4001 ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID); 4002 4003 ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult); 4004 } 4005 4006 /** 4007 * Adds a new network and verifies that the |HasEverConnected| flag is set to false. 4008 */ 4009 private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) { 4010 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 4011 WifiConfiguration retrievedNetwork = 4012 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 4013 assertFalse("Adding a new network should not have hasEverConnected set to true.", 4014 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 4015 } 4016 4017 /** 4018 * Updates an existing network with some credential change and verifies that the 4019 * |HasEverConnected| flag is set to false. 4020 */ 4021 private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse( 4022 WifiConfiguration network) { 4023 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 4024 WifiConfiguration retrievedNetwork = 4025 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 4026 assertFalse("Updating network credentials config should clear hasEverConnected.", 4027 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 4028 assertTrue(result.hasCredentialChanged()); 4029 } 4030 4031 /** 4032 * Updates an existing network after connection using 4033 * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the 4034 * |HasEverConnected| flag is set to true. 4035 */ 4036 private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) { 4037 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId)); 4038 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 4039 assertTrue("hasEverConnected expected to be true after connection.", 4040 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 4041 } 4042 4043 /** 4044 * Sets up a user profiles for WifiConfigManager testing. 4045 * 4046 * @param userId Id of the user. 4047 */ 4048 private void setupUserProfiles(int userId) { 4049 final UserInfo userInfo = 4050 new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY); 4051 List<UserInfo> userProfiles = Arrays.asList(userInfo); 4052 when(mUserManager.getProfiles(userId)).thenReturn(userProfiles); 4053 when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true); 4054 } 4055 4056} 4057