1 /*
2  * Copyright (C) 2018 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 
17 package com.android.server.wifi;
18 
19 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
20 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
21 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE;
22 import static android.net.NetworkFactory.CMD_REQUEST_NETWORK;
23 
24 import static com.android.server.wifi.WifiNetworkFactory.PERIODIC_SCAN_INTERVAL_MS;
25 import static com.android.server.wifi.util.NativeUtil.addEnclosingQuotes;
26 
27 import static org.junit.Assert.*;
28 import static org.mockito.Mockito.*;
29 
30 import android.annotation.Nullable;
31 import android.app.ActivityManager;
32 import android.app.AlarmManager;
33 import android.app.AlarmManager.OnAlarmListener;
34 import android.app.AppOpsManager;
35 import android.content.Context;
36 import android.content.Intent;
37 import android.content.pm.ApplicationInfo;
38 import android.content.pm.PackageManager;
39 import android.net.ConnectivityManager;
40 import android.net.MacAddress;
41 import android.net.NetworkCapabilities;
42 import android.net.NetworkFactory;
43 import android.net.NetworkRequest;
44 import android.net.wifi.INetworkRequestMatchCallback;
45 import android.net.wifi.INetworkRequestUserSelectionCallback;
46 import android.net.wifi.ScanResult;
47 import android.net.wifi.WifiConfiguration;
48 import android.net.wifi.WifiManager;
49 import android.net.wifi.WifiNetworkSpecifier;
50 import android.net.wifi.WifiScanner;
51 import android.net.wifi.WifiScanner.ScanListener;
52 import android.net.wifi.WifiScanner.ScanSettings;
53 import android.os.IBinder;
54 import android.os.Message;
55 import android.os.Messenger;
56 import android.os.PatternMatcher;
57 import android.os.Process;
58 import android.os.RemoteException;
59 import android.os.UserHandle;
60 import android.os.WorkSource;
61 import android.os.test.TestLooper;
62 import android.test.suitebuilder.annotation.SmallTest;
63 import android.util.Pair;
64 
65 import com.android.internal.util.AsyncChannel;
66 import com.android.server.wifi.WifiNetworkFactory.AccessPoint;
67 import com.android.server.wifi.nano.WifiMetricsProto;
68 import com.android.server.wifi.util.ScanResultUtil;
69 import com.android.server.wifi.util.WifiPermissionsUtil;
70 
71 import org.junit.After;
72 import org.junit.Before;
73 import org.junit.Test;
74 import org.mockito.ArgumentCaptor;
75 import org.mockito.ArgumentMatcher;
76 import org.mockito.InOrder;
77 import org.mockito.Mock;
78 import org.mockito.MockitoAnnotations;
79 
80 import java.util.HashMap;
81 import java.util.HashSet;
82 import java.util.List;
83 import java.util.Map;
84 import java.util.Set;
85 
86 /**
87  * Unit tests for {@link com.android.server.wifi.WifiNetworkFactory}.
88  */
89 @SmallTest
90 public class WifiNetworkFactoryTest {
91     private static final int TEST_NETWORK_ID_1 = 104;
92     private static final int TEST_UID_1 = 10423;
93     private static final int TEST_UID_2 = 10424;
94     private static final int TEST_CALLBACK_IDENTIFIER = 123;
95     private static final String TEST_PACKAGE_NAME_1 = "com.test.networkrequest.1";
96     private static final String TEST_PACKAGE_NAME_2 = "com.test.networkrequest.2";
97     private static final String TEST_APP_NAME = "app";
98     private static final String TEST_SSID_1 = "test1234";
99     private static final String TEST_SSID_2 = "test12345678";
100     private static final String TEST_SSID_3 = "abc1234";
101     private static final String TEST_SSID_4 = "abc12345678";
102     private static final String TEST_BSSID_1 = "12:34:23:23:45:ac";
103     private static final String TEST_BSSID_2 = "12:34:23:32:12:67";
104     private static final String TEST_BSSID_3 = "45:34:34:12:bb:dd";
105     private static final String TEST_BSSID_4 = "45:34:34:56:ee:ff";
106     private static final String TEST_BSSID_1_2_OUI = "12:34:23:00:00:00";
107     private static final String TEST_BSSID_OUI_MASK = "ff:ff:ff:00:00:00";
108     private static final String TEST_WPA_PRESHARED_KEY = "\"password123\"";
109 
110     @Mock Context mContext;
111     @Mock ActivityManager mActivityManager;
112     @Mock AlarmManager mAlarmManager;
113     @Mock AppOpsManager mAppOpsManager;
114     @Mock Clock mClock;
115     @Mock WifiInjector mWifiInjector;
116     @Mock WifiConnectivityManager mWifiConnectivityManager;
117     @Mock WifiConfigManager mWifiConfigManager;
118     @Mock WifiConfigStore mWifiConfigStore;
119     @Mock WifiPermissionsUtil mWifiPermissionsUtil;
120     @Mock WifiScanner mWifiScanner;
121     @Mock PackageManager mPackageManager;
122     @Mock IBinder mAppBinder;
123     @Mock INetworkRequestMatchCallback mNetworkRequestMatchCallback;
124     @Mock ClientModeImpl mClientModeImpl;
125     @Mock ConnectivityManager mConnectivityManager;
126     @Mock WifiMetrics mWifiMetrics;
127     @Mock Messenger mConnectivityMessenger;
128     NetworkCapabilities mNetworkCapabilities;
129     TestLooper mLooper;
130     NetworkRequest mNetworkRequest;
131     WifiScanner.ScanData[] mTestScanDatas;
132     WifiConfiguration mSelectedNetwork;
133     ArgumentCaptor<ScanSettings> mScanSettingsArgumentCaptor =
134             ArgumentCaptor.forClass(ScanSettings.class);
135     ArgumentCaptor<WorkSource> mWorkSourceArgumentCaptor =
136             ArgumentCaptor.forClass(WorkSource.class);
137     ArgumentCaptor<INetworkRequestUserSelectionCallback> mNetworkRequestUserSelectionCallback =
138             ArgumentCaptor.forClass(INetworkRequestUserSelectionCallback.class);
139     ArgumentCaptor<OnAlarmListener> mPeriodicScanListenerArgumentCaptor =
140             ArgumentCaptor.forClass(OnAlarmListener.class);
141     ArgumentCaptor<OnAlarmListener> mConnectionTimeoutAlarmListenerArgumentCaptor =
142             ArgumentCaptor.forClass(OnAlarmListener.class);
143     ArgumentCaptor<ScanListener> mScanListenerArgumentCaptor =
144             ArgumentCaptor.forClass(ScanListener.class);
145     InOrder mInOrder;
146 
147     private WifiNetworkFactory mWifiNetworkFactory;
148     private NetworkRequestStoreData.DataSource mDataSource;
149 
150     /**
151      * Setup the mocks.
152      */
153     @Before
setUp()154     public void setUp() throws Exception {
155         MockitoAnnotations.initMocks(this);
156 
157         mLooper = new TestLooper();
158         mNetworkCapabilities = new NetworkCapabilities();
159         mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
160         mTestScanDatas = ScanTestUtil.createScanDatas(new int[][]{ { 2417, 2427, 5180, 5170 } });
161 
162         when(mContext.getPackageManager()).thenReturn(mPackageManager);
163         when(mContext.getSystemService(eq(Context.CONNECTIVITY_SERVICE)))
164                 .thenReturn(mConnectivityManager);
165         when(mPackageManager.getNameForUid(TEST_UID_1)).thenReturn(TEST_PACKAGE_NAME_1);
166         when(mPackageManager.getNameForUid(TEST_UID_2)).thenReturn(TEST_PACKAGE_NAME_2);
167         when(mPackageManager.getApplicationInfo(any(), anyInt())).thenReturn(new ApplicationInfo());
168         when(mPackageManager.getApplicationLabel(any())).thenReturn(TEST_APP_NAME);
169         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
170                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
171         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
172                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
173         when(mWifiInjector.getWifiScanner()).thenReturn(mWifiScanner);
174         when(mWifiInjector.getClientModeImpl()).thenReturn(mClientModeImpl);
175         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString()))
176                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID_1));
177 
178         mWifiNetworkFactory = new WifiNetworkFactory(mLooper.getLooper(), mContext,
179                 mNetworkCapabilities, mActivityManager, mAlarmManager, mAppOpsManager, mClock,
180                 mWifiInjector, mWifiConnectivityManager, mWifiConfigManager, mWifiConfigStore,
181                 mWifiPermissionsUtil, mWifiMetrics);
182 
183         ArgumentCaptor<NetworkRequestStoreData.DataSource> dataSourceArgumentCaptor =
184                 ArgumentCaptor.forClass(NetworkRequestStoreData.DataSource.class);
185         verify(mWifiInjector).makeNetworkRequestStoreData(dataSourceArgumentCaptor.capture());
186         mDataSource = dataSourceArgumentCaptor.getValue();
187         assertNotNull(mDataSource);
188 
189         // Register and establish full connection to connectivity manager.
190         mWifiNetworkFactory.register();
191         ArgumentCaptor<Messenger> messengerArgumentCaptor =
192                 ArgumentCaptor.forClass(Messenger.class);
193         verify(mConnectivityManager).registerNetworkFactory(
194                 messengerArgumentCaptor.capture(), anyString());
195         assertNotNull(messengerArgumentCaptor.getValue());
196         Message fullConnectionMsg = Message.obtain();
197         fullConnectionMsg.what = AsyncChannel.CMD_CHANNEL_FULL_CONNECTION;
198         fullConnectionMsg.replyTo = mConnectivityMessenger;
199         messengerArgumentCaptor.getValue().send(fullConnectionMsg);
200         mLooper.dispatchAll();
201 
202         mNetworkRequest = new NetworkRequest.Builder()
203                 .setCapabilities(mNetworkCapabilities)
204                 .build();
205 
206         // Setup with wifi on.
207         mWifiNetworkFactory.setWifiState(true);
208         mWifiNetworkFactory.enableVerboseLogging(1);
209     }
210 
211     /**
212      * Called after each test
213      */
214     @After
cleanup()215     public void cleanup() {
216         validateMockitoUsage();
217     }
218 
219     /**
220      * Validates handling of needNetworkFor.
221      */
222     @Test
testHandleNetworkRequestWithNoSpecifier()223     public void testHandleNetworkRequestWithNoSpecifier() {
224         assertFalse(mWifiNetworkFactory.hasConnectionRequests());
225         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
226 
227         // First network request should turn on auto-join.
228         verify(mWifiConnectivityManager).setTrustedConnectionAllowed(true);
229         assertTrue(mWifiNetworkFactory.hasConnectionRequests());
230 
231         // Subsequent ones should do nothing.
232         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
233         verifyNoMoreInteractions(mWifiConnectivityManager);
234     }
235 
236     /**
237      * Validates handling of releaseNetwork.
238      */
239     @Test
testHandleNetworkReleaseWithNoSpecifier()240     public void testHandleNetworkReleaseWithNoSpecifier() {
241         // Release network with out a corresponding request should be ignored.
242         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
243         assertFalse(mWifiNetworkFactory.hasConnectionRequests());
244 
245         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
246         assertTrue(mWifiNetworkFactory.hasConnectionRequests());
247         verify(mWifiConnectivityManager).setTrustedConnectionAllowed(true);
248 
249         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
250         assertFalse(mWifiNetworkFactory.hasConnectionRequests());
251         verify(mWifiConnectivityManager).setTrustedConnectionAllowed(false);
252     }
253 
254     /**
255      * Validates handling of acceptNetwork for requests with no network specifier.
256      */
257     @Test
testHandleAcceptNetworkRequestWithNoSpecifier()258     public void testHandleAcceptNetworkRequestWithNoSpecifier() {
259         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
260     }
261 
262     /**
263      * Validates handling of acceptNetwork with a network specifier with invalid uid/package name.
264      */
265     @Test
testHandleAcceptNetworkRequestFromWithInvalidSpecifier()266     public void testHandleAcceptNetworkRequestFromWithInvalidSpecifier() throws Exception {
267         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
268                 .thenReturn(IMPORTANCE_GONE);
269         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(TEST_UID_1))
270                 .thenReturn(true);
271         doThrow(new SecurityException()).when(mAppOpsManager).checkPackage(anyInt(), anyString());
272 
273         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
274         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
275 
276         assertFalse(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
277         mLooper.dispatchAll();
278         verifyUnfullfillableDispatched(mConnectivityMessenger);
279     }
280 
281     /**
282      * Validates handling of acceptNetwork with a network specifier with internet capability.
283      */
284     @Test
testHandleAcceptNetworkRequestFromWithInternetCapability()285     public void testHandleAcceptNetworkRequestFromWithInternetCapability() throws Exception {
286         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
287                 .thenReturn(IMPORTANCE_FOREGROUND);
288 
289         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
290         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
291         mNetworkRequest.networkCapabilities.addCapability(
292                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
293 
294         assertFalse(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
295         mLooper.dispatchAll();
296         verifyUnfullfillableDispatched(mConnectivityMessenger);
297     }
298 
299     /**
300      * Validates handling of acceptNetwork with a network specifier from a non foreground
301      * app/service.
302      */
303     @Test
testHandleAcceptNetworkRequestFromNonFgAppOrSvcWithSpecifier()304     public void testHandleAcceptNetworkRequestFromNonFgAppOrSvcWithSpecifier() throws Exception {
305         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
306                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE + 1);
307 
308         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
309         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
310 
311         assertFalse(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
312         mLooper.dispatchAll();
313         verifyUnfullfillableDispatched(mConnectivityMessenger);
314     }
315 
316     /**
317      * Validates handling of acceptNetwork with a network specifier from a foreground
318      * app.
319      */
320     @Test
testHandleAcceptNetworkRequestFromFgAppWithSpecifier()321     public void testHandleAcceptNetworkRequestFromFgAppWithSpecifier() {
322         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
323                 .thenReturn(IMPORTANCE_FOREGROUND);
324 
325         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
326         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
327 
328         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
329     }
330 
331     /**
332      * Validates handling of acceptNetwork with a network specifier from apps holding
333      * NETWORK_SETTINGS.
334      */
335     @Test
testHandleAcceptNetworkRequestFromNetworkSettingAppWithSpecifier()336     public void testHandleAcceptNetworkRequestFromNetworkSettingAppWithSpecifier() {
337         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
338                 .thenReturn(IMPORTANCE_GONE);
339         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(TEST_UID_1))
340                 .thenReturn(true);
341 
342         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
343         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
344 
345         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
346     }
347 
348     /**
349      * Validates handling of acceptNetwork with a network specifier from a foreground
350      * app.
351      */
352     @Test
testHandleAcceptNetworkRequestFromFgAppWithSpecifierWithPendingRequestFromFgSvc()353     public void testHandleAcceptNetworkRequestFromFgAppWithSpecifierWithPendingRequestFromFgSvc() {
354         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
355                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
356         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
357                 .thenReturn(IMPORTANCE_FOREGROUND);
358 
359         // Handle request 1.
360         WifiNetworkSpecifier specifier1 = createWifiNetworkSpecifier(TEST_UID_1, false);
361         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
362         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
363 
364         // Make request 2 which will be accepted because a fg app request can
365         // override a fg service request.
366         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
367         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
368         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
369     }
370 
371     /**
372      * Validates handling of acceptNetwork with a network specifier from a foreground
373      * app.
374      */
375     @Test
testHandleAcceptNetworkRequestFromFgSvcWithSpecifierWithPendingRequestFromFgSvc()376     public void testHandleAcceptNetworkRequestFromFgSvcWithSpecifierWithPendingRequestFromFgSvc() {
377         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
378                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
379         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
380                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
381 
382         // Handle request 1.
383         WifiNetworkSpecifier specifier1 = createWifiNetworkSpecifier(TEST_UID_1, false);
384         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
385         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
386 
387         // Make request 2 which will be accepted because a fg service request can
388         // override an existing fg service request.
389         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
390         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
391         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
392     }
393 
394     /**
395      * Validates handling of acceptNetwork with a network specifier from a foreground
396      * app.
397      */
398     @Test
testHandleAcceptNetworkRequestFromFgAppWithSpecifierWithPendingRequestFromFgApp()399     public void testHandleAcceptNetworkRequestFromFgAppWithSpecifierWithPendingRequestFromFgApp() {
400         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
401                 .thenReturn(IMPORTANCE_FOREGROUND);
402         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
403                 .thenReturn(IMPORTANCE_FOREGROUND);
404 
405         // Handle request 1.
406         WifiNetworkSpecifier specifier1 = createWifiNetworkSpecifier(TEST_UID_1, false);
407         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
408         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
409 
410         // Make request 2 which will be accepted because a fg app request can
411         // override an existing fg app request.
412         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
413         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
414         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
415     }
416 
417     /**
418      * Validates handling of acceptNetwork with a network specifier from a foreground
419      * service when we're in the midst of processing a request from a foreground app.
420      */
421     @Test
testHandleAcceptNetworkRequestFromFgSvcWithSpecifierWithPendingRequestFromFgApp()422     public void testHandleAcceptNetworkRequestFromFgSvcWithSpecifierWithPendingRequestFromFgApp()
423             throws Exception {
424         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
425                 .thenReturn(IMPORTANCE_FOREGROUND);
426         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
427                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
428 
429         // Handle request 1.
430         WifiNetworkSpecifier specifier1 = createWifiNetworkSpecifier(TEST_UID_1, false);
431         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
432         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
433 
434         // Make request 2 which will be rejected because a fg service request cannot
435         // override a fg app request.
436         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
437         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
438         assertFalse(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
439         mLooper.dispatchAll();
440         verifyUnfullfillableDispatched(mConnectivityMessenger);
441     }
442 
443     /**
444      * Validates handling of acceptNetwork with a network specifier from a foreground
445      * app when we're connected to a request from a foreground app.
446      */
447     @Test
448     public void
testHandleAcceptNetworkRequestFromFgAppWithSpecifierWithConnectedRequestFromFgApp()449             testHandleAcceptNetworkRequestFromFgAppWithSpecifierWithConnectedRequestFromFgApp()
450             throws Exception {
451         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
452                 .thenReturn(IMPORTANCE_FOREGROUND);
453         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
454                 .thenReturn(IMPORTANCE_FOREGROUND);
455 
456         // Connect to request 1
457         sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
458         // Send network connection success indication.
459         assertNotNull(mSelectedNetwork);
460         mWifiNetworkFactory.handleConnectionAttemptEnded(
461                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
462 
463         // Make request 2 which will be accepted because a fg app request can
464         // override an existing fg app request.
465         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
466         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
467         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
468     }
469 
470     /**
471      * Validates handling of acceptNetwork with a network specifier from a foreground
472      * service when we're connected to a request from a foreground app.
473      */
474     @Test
475     public void
testHandleAcceptNetworkRequestFromFgSvcWithSpecifierWithConnectedRequestFromFgApp()476             testHandleAcceptNetworkRequestFromFgSvcWithSpecifierWithConnectedRequestFromFgApp()
477             throws Exception {
478         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
479                 .thenReturn(IMPORTANCE_FOREGROUND);
480         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_2))
481                 .thenReturn(IMPORTANCE_FOREGROUND_SERVICE);
482 
483         // Connect to request 1
484         sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
485         // Send network connection success indication.
486         assertNotNull(mSelectedNetwork);
487         mWifiNetworkFactory.handleConnectionAttemptEnded(
488                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
489 
490         // Make request 2 which will be rejected because a fg service request cannot
491         // override a fg app request.
492         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
493         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
494         assertFalse(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
495         mLooper.dispatchAll();
496         verifyUnfullfillableDispatched(mConnectivityMessenger);
497     }
498 
499     /**
500      * Verify handling of new network request with network specifier.
501      */
502     @Test
testHandleNetworkRequestWithSpecifier()503     public void testHandleNetworkRequestWithSpecifier() {
504         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
505         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
506         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
507 
508         // Verify UI start.
509         validateUiStartParams(true);
510 
511         // Verify scan settings.
512         verify(mWifiScanner).startScan(mScanSettingsArgumentCaptor.capture(), any(),
513                 mWorkSourceArgumentCaptor.capture());
514         validateScanSettings(null);
515 
516         verify(mWifiMetrics).incrementNetworkRequestApiNumRequest();
517     }
518 
519     /**
520      * Validates handling of new network request with network specifier with internet capability.
521      */
522     @Test
testHandleNetworkRequestWithSpecifierAndInternetCapability()523     public void testHandleNetworkRequestWithSpecifierAndInternetCapability() throws Exception {
524         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
525         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
526         mNetworkRequest.networkCapabilities.addCapability(
527                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
528 
529         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
530         mLooper.dispatchAll();
531         verifyUnfullfillableDispatched(mConnectivityMessenger);
532     }
533 
534     /**
535      * Verify handling of new network request with network specifier for a hidden network.
536      */
537     @Test
testHandleNetworkRequestWithSpecifierForHiddenNetwork()538     public void testHandleNetworkRequestWithSpecifierForHiddenNetwork() {
539         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, true);
540         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
541         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
542 
543         // Verify UI start.
544         validateUiStartParams(true);
545 
546         // Verify scan settings.
547         verify(mWifiScanner).startScan(mScanSettingsArgumentCaptor.capture(), any(),
548                 mWorkSourceArgumentCaptor.capture());
549         validateScanSettings(specifier.ssidPatternMatcher.getPath());
550 
551         verify(mWifiMetrics).incrementNetworkRequestApiNumRequest();
552     }
553 
554     /**
555      * Verify handling of new network request with network specifier for a non-hidden network
556      * after processing a previous hidden network requst.
557      * Validates that the scan settings was properly reset between the 2 request
558      * {@link ScanSettings#hiddenNetworks}
559      */
560     @Test
testHandleNetworkRequestWithSpecifierAfterPreviousHiddenNetworkRequest()561     public void testHandleNetworkRequestWithSpecifierAfterPreviousHiddenNetworkRequest() {
562         // Hidden request 1.
563         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, true);
564         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
565         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
566         // Verify scan settings.
567         verify(mWifiScanner, times(1)).startScan(mScanSettingsArgumentCaptor.capture(), any(),
568                 mWorkSourceArgumentCaptor.capture());
569         validateScanSettings(specifier.ssidPatternMatcher.getPath());
570 
571         // Release request 1.
572         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
573 
574         // Regular request 2.
575         specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
576         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
577         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
578         // Verify scan settings.
579         verify(mWifiScanner, times(2)).startScan(mScanSettingsArgumentCaptor.capture(), any(),
580                 mWorkSourceArgumentCaptor.capture());
581         validateScanSettings(null);
582 
583         verify(mWifiMetrics, times(2)).incrementNetworkRequestApiNumRequest();
584     }
585 
586     /**
587      * Verify handling of release of the active network request with network specifier.
588      */
589     @Test
testHandleNetworkReleaseWithSpecifier()590     public void testHandleNetworkReleaseWithSpecifier() {
591         // Make a generic request first to ensure that we re-enable auto-join after release.
592         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
593 
594         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
595         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
596 
597         // Make the network request with specifier.
598         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
599         verify(mWifiScanner).startScan(any(), any(), any());
600 
601         // Release the network request.
602         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
603         // Verify that we did not trigger a disconnect because we've not yet connected.
604         verify(mClientModeImpl, never()).disconnectCommand();
605         // Re-enable connectivity manager .
606         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
607 
608         verify(mWifiMetrics).incrementNetworkRequestApiNumRequest();
609     }
610 
611     /**
612      * Verify the periodic scan to find a network matching the network specifier.
613      * Simulates the case where the network is not found in any of the scan results.
614      */
615     @Test
testPeriodicScanNetworkRequestWithSpecifier()616     public void testPeriodicScanNetworkRequestWithSpecifier() {
617         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
618         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
619         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
620 
621         verifyPeriodicScans(0,
622                 PERIODIC_SCAN_INTERVAL_MS,     // 10s
623                 PERIODIC_SCAN_INTERVAL_MS,     // 10s
624                 PERIODIC_SCAN_INTERVAL_MS,     // 10s
625                 PERIODIC_SCAN_INTERVAL_MS);    // 10s
626     }
627 
628     /**
629      * Verify the periodic scan back off to find a network matching the network specifier
630      * is cancelled when the active network request is released.
631      */
632     @Test
testPeriodicScanCancelOnReleaseNetworkRequestWithSpecifier()633     public void testPeriodicScanCancelOnReleaseNetworkRequestWithSpecifier() {
634         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
635         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
636         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
637 
638         verifyPeriodicScans(0,
639                 PERIODIC_SCAN_INTERVAL_MS,     // 10s
640                 PERIODIC_SCAN_INTERVAL_MS);    // 10s
641 
642         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
643         // Cancel the alarm set for the next scan.
644         verify(mAlarmManager).cancel(any(OnAlarmListener.class));
645     }
646 
647     /**
648      * Verify callback registration/unregistration.
649      */
650     @Test
testHandleCallbackRegistrationAndUnregistration()651     public void testHandleCallbackRegistrationAndUnregistration() throws Exception {
652         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
653         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
654         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
655 
656         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
657                 TEST_CALLBACK_IDENTIFIER);
658 
659         //Ensure that we register the user selection callback using the newly registered callback.
660         verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
661                 any(INetworkRequestUserSelectionCallback.class));
662 
663         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
664 
665         verifyNoMoreInteractions(mNetworkRequestMatchCallback);
666     }
667 
668     /**
669      * Verify callback registration when the active request has already been released..
670      */
671     @Test
testHandleCallbackRegistrationWithNoActiveRequest()672     public void testHandleCallbackRegistrationWithNoActiveRequest() throws Exception {
673         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
674         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
675         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
676         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
677 
678         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
679                 TEST_CALLBACK_IDENTIFIER);
680 
681         //Ensure that we trigger the onAbort callback & nothing else.
682         verify(mNetworkRequestMatchCallback).onAbort();
683 
684         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
685 
686         verifyNoMoreInteractions(mNetworkRequestMatchCallback);
687     }
688 
689     /**
690      * Verify network specifier matching for a specifier containing a specific SSID match using
691      * 4 WPA_PSK scan results, each with unique SSID.
692      */
693     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidMatch()694     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidMatch() throws Exception {
695         // Setup scan data for open networks.
696         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
697                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
698 
699         // Setup network specifier for open networks.
700         PatternMatcher ssidPatternMatch =
701                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
702         Pair<MacAddress, MacAddress> bssidPatternMatch =
703                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
704         WifiConfiguration wifiConfiguration = new WifiConfiguration();
705         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
706         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
707                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
708                 TEST_PACKAGE_NAME_1);
709 
710         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
711         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
712 
713         validateUiStartParams(true);
714 
715         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
716                 TEST_CALLBACK_IDENTIFIER);
717 
718         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
719 
720         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
721                 ArgumentCaptor.forClass(List.class);
722         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
723 
724         assertNotNull(matchedScanResultsCaptor.getValue());
725         // We only expect 1 network match in this case.
726         validateScanResults(matchedScanResultsCaptor.getValue(), mTestScanDatas[0].getResults()[0]);
727 
728         verify(mWifiMetrics).incrementNetworkRequestApiMatchSizeHistogram(
729                 matchedScanResultsCaptor.getValue().size());
730     }
731 
732     /**
733      * Verify network specifier matching for a specifier containing a Prefix SSID match using
734      * 4 open scan results, each with unique SSID.
735      */
736     @Test
testNetworkSpecifierMatchSuccessUsingPrefixSsidMatch()737     public void testNetworkSpecifierMatchSuccessUsingPrefixSsidMatch() throws Exception {
738         // Setup scan data for open networks.
739         setupScanData(SCAN_RESULT_TYPE_OPEN,
740                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
741 
742         // Setup network specifier for open networks.
743         PatternMatcher ssidPatternMatch =
744                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_PREFIX);
745         Pair<MacAddress, MacAddress> bssidPatternMatch =
746                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
747         WifiConfiguration wifiConfiguration = new WifiConfiguration();
748         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
749         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
750                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
751                 TEST_PACKAGE_NAME_1);
752 
753         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
754         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
755 
756         validateUiStartParams(false);
757 
758         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
759                 TEST_CALLBACK_IDENTIFIER);
760 
761         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
762 
763         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
764                 ArgumentCaptor.forClass(List.class);
765         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
766 
767         assertNotNull(matchedScanResultsCaptor.getValue());
768         // We expect 2 scan result matches in this case.
769         validateScanResults(matchedScanResultsCaptor.getValue(),
770                 mTestScanDatas[0].getResults()[0], mTestScanDatas[0].getResults()[1]);
771 
772         verify(mWifiMetrics).incrementNetworkRequestApiMatchSizeHistogram(
773                 matchedScanResultsCaptor.getValue().size());
774     }
775 
776     /**
777      * Verify network specifier matching for a specifier containing a specific BSSID match using
778      * 4 WPA_PSK scan results, each with unique SSID.
779      */
780     @Test
testNetworkSpecifierMatchSuccessUsingLiteralBssidMatch()781     public void testNetworkSpecifierMatchSuccessUsingLiteralBssidMatch() throws Exception {
782         // Setup scan data for open networks.
783         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
784                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
785 
786         // Setup network specifier for open networks.
787         PatternMatcher ssidPatternMatch =
788                 new PatternMatcher(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
789         Pair<MacAddress, MacAddress> bssidPatternMatch =
790                 Pair.create(MacAddress.fromString(TEST_BSSID_1), MacAddress.BROADCAST_ADDRESS);
791         WifiConfiguration wifiConfiguration = new WifiConfiguration();
792         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
793         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
794                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
795                 TEST_PACKAGE_NAME_1);
796 
797         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
798         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
799 
800         validateUiStartParams(true);
801 
802         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
803                 TEST_CALLBACK_IDENTIFIER);
804 
805         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
806 
807         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
808                 ArgumentCaptor.forClass(List.class);
809         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
810 
811         assertNotNull(matchedScanResultsCaptor.getValue());
812         // We only expect 1 scan result match in this case.
813         validateScanResults(matchedScanResultsCaptor.getValue(), mTestScanDatas[0].getResults()[0]);
814 
815         verify(mWifiMetrics).incrementNetworkRequestApiMatchSizeHistogram(
816                 matchedScanResultsCaptor.getValue().size());
817     }
818 
819     /**
820      * Verify network specifier matching for a specifier containing a prefix BSSID match using
821      * 4 WPA_EAP scan results, each with unique SSID.
822      */
823     @Test
testNetworkSpecifierMatchSuccessUsingOuiPrefixBssidMatch()824     public void testNetworkSpecifierMatchSuccessUsingOuiPrefixBssidMatch() throws Exception {
825         // Setup scan data for open networks.
826         setupScanData(SCAN_RESULT_TYPE_WPA_EAP,
827                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
828 
829         // Setup network specifier for open networks.
830         PatternMatcher ssidPatternMatch =
831                 new PatternMatcher(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
832         Pair<MacAddress, MacAddress> bssidPatternMatch =
833                 Pair.create(MacAddress.fromString(TEST_BSSID_1_2_OUI),
834                         MacAddress.fromString(TEST_BSSID_OUI_MASK));
835         WifiConfiguration wifiConfiguration = new WifiConfiguration();
836         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
837         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
838                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
839                 TEST_PACKAGE_NAME_1);
840 
841         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
842         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
843 
844         validateUiStartParams(false);
845 
846         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
847                 TEST_CALLBACK_IDENTIFIER);
848 
849         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
850 
851         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
852                 ArgumentCaptor.forClass(List.class);
853         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
854 
855         assertNotNull(matchedScanResultsCaptor.getValue());
856         // We expect 2 scan result matches in this case.
857         validateScanResults(matchedScanResultsCaptor.getValue(),
858                 mTestScanDatas[0].getResults()[0], mTestScanDatas[0].getResults()[1]);
859 
860         verify(mWifiMetrics).incrementNetworkRequestApiMatchSizeHistogram(
861                 matchedScanResultsCaptor.getValue().size());
862     }
863 
864     /**
865      * Verify network specifier matching for a specifier containing a specific SSID match using
866      * 4 WPA_PSK scan results, 3 of which have the same SSID.
867      */
868     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidMatchWithMultipleBssidMatches()869     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidMatchWithMultipleBssidMatches()
870             throws Exception {
871         // Setup scan data for open networks.
872         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
873                 TEST_SSID_1, TEST_SSID_1, TEST_SSID_1, TEST_SSID_2);
874 
875         // Setup network specifier for open networks.
876         PatternMatcher ssidPatternMatch =
877                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
878         Pair<MacAddress, MacAddress> bssidPatternMatch =
879                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
880         WifiConfiguration wifiConfiguration = new WifiConfiguration();
881         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
882         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
883                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
884                 TEST_PACKAGE_NAME_1);
885 
886         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
887         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
888 
889         validateUiStartParams(true);
890 
891         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
892                 TEST_CALLBACK_IDENTIFIER);
893 
894         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
895 
896         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
897                 ArgumentCaptor.forClass(List.class);
898         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
899 
900         assertNotNull(matchedScanResultsCaptor.getValue());
901         // We expect 3 scan result matches in this case.
902         validateScanResults(matchedScanResultsCaptor.getValue(),
903                 mTestScanDatas[0].getResults()[0], mTestScanDatas[0].getResults()[1],
904                 mTestScanDatas[0].getResults()[2]);
905 
906         verify(mWifiMetrics).incrementNetworkRequestApiMatchSizeHistogram(
907                 matchedScanResultsCaptor.getValue().size());
908     }
909 
910     /**
911      * Verify network specifier match failure for a specifier containing a specific SSID match using
912      * 4 WPA_PSK scan results, 2 of which SSID_1 and the other 2 SSID_2. But, none of the scan
913      * results' SSID match the one requested in the specifier.
914      */
915     @Test
testNetworkSpecifierMatchFailUsingLiteralSsidMatchWhenSsidNotFound()916     public void testNetworkSpecifierMatchFailUsingLiteralSsidMatchWhenSsidNotFound()
917             throws Exception {
918         // Setup scan data for open networks.
919         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
920                 TEST_SSID_1, TEST_SSID_1, TEST_SSID_2, TEST_SSID_2);
921 
922         // Setup network specifier for open networks.
923         PatternMatcher ssidPatternMatch =
924                 new PatternMatcher(TEST_SSID_3, PatternMatcher.PATTERN_LITERAL);
925         Pair<MacAddress, MacAddress> bssidPatternMatch =
926                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
927         WifiConfiguration wifiConfiguration = new WifiConfiguration();
928         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
929         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
930                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
931                 TEST_PACKAGE_NAME_1);
932 
933         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
934         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
935 
936         validateUiStartParams(true);
937 
938         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
939                 TEST_CALLBACK_IDENTIFIER);
940 
941         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
942 
943         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
944                 ArgumentCaptor.forClass(List.class);
945         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
946 
947         assertNotNull(matchedScanResultsCaptor.getValue());
948         // We expect no network match in this case.
949         assertEquals(0, matchedScanResultsCaptor.getValue().size());
950 
951         verify(mWifiMetrics).incrementNetworkRequestApiMatchSizeHistogram(
952                 matchedScanResultsCaptor.getValue().size());
953     }
954 
955     /**
956      * Verify network specifier match failure for a specifier containing a specific SSID match using
957      * 4 open scan results, each with unique SSID. But, none of the scan
958      * results' key mgmt match the one requested in the specifier.
959      */
960     @Test
testNetworkSpecifierMatchFailUsingLiteralSsidMatchWhenKeyMgmtDiffers()961     public void testNetworkSpecifierMatchFailUsingLiteralSsidMatchWhenKeyMgmtDiffers()
962             throws Exception {
963         // Setup scan data for open networks.
964         setupScanData(SCAN_RESULT_TYPE_OPEN,
965                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
966 
967         // Setup network specifier for open networks.
968         PatternMatcher ssidPatternMatch =
969                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
970         Pair<MacAddress, MacAddress> bssidPatternMatch =
971                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
972         WifiConfiguration wifiConfiguration = new WifiConfiguration();
973         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
974         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
975                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
976                 TEST_PACKAGE_NAME_1);
977 
978         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
979         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
980 
981         validateUiStartParams(true);
982 
983         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
984                 TEST_CALLBACK_IDENTIFIER);
985 
986         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
987 
988         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
989                 ArgumentCaptor.forClass(List.class);
990         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
991 
992         assertNotNull(matchedScanResultsCaptor.getValue());
993         // We expect no network match in this case.
994         assertEquals(0, matchedScanResultsCaptor.getValue().size());
995     }
996 
997     /**
998      * Verify handling of stale user selection (previous request released).
999      */
1000     @Test
testNetworkSpecifierHandleUserSelectionConnectToNetworkWithoutActiveRequest()1001     public void testNetworkSpecifierHandleUserSelectionConnectToNetworkWithoutActiveRequest()
1002             throws Exception {
1003         sendNetworkRequestAndSetupForUserSelection();
1004 
1005         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1006                 mNetworkRequestUserSelectionCallback.getValue();
1007         assertNotNull(networkRequestUserSelectionCallback);
1008 
1009         // Now release the active network request.
1010         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1011         // Re-enable connectivity manager (if it was disabled).
1012         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1013 
1014         // Now trigger user selection to some network.
1015         WifiConfiguration selectedNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1016         networkRequestUserSelectionCallback.select(selectedNetwork);
1017         mLooper.dispatchAll();
1018 
1019         // Verify we did not attempt to trigger a connection or disable connectivity manager.
1020         verifyNoMoreInteractions(mClientModeImpl, mWifiConnectivityManager);
1021     }
1022 
1023     /**
1024      * Verify handling of stale user selection (new request replacing the previous request).
1025      */
1026     @Test
testNetworkSpecifierHandleUserSelectionConnectToNetworkWithDifferentActiveRequest()1027     public void testNetworkSpecifierHandleUserSelectionConnectToNetworkWithDifferentActiveRequest()
1028             throws Exception {
1029         sendNetworkRequestAndSetupForUserSelection();
1030 
1031         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1032                 mNetworkRequestUserSelectionCallback.getValue();
1033         assertNotNull(networkRequestUserSelectionCallback);
1034 
1035         // Now send another network request.
1036         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1037 
1038         // Now trigger user selection to some network.
1039         WifiConfiguration selectedNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1040         networkRequestUserSelectionCallback.select(selectedNetwork);
1041         mLooper.dispatchAll();
1042 
1043         // Verify we did not attempt to trigger a connection or disable connectivity manager.
1044         verifyNoMoreInteractions(mClientModeImpl, mWifiConnectivityManager, mWifiConfigManager);
1045     }
1046 
1047     /**
1048      * Verify handling of user selection to trigger connection to a network.
1049      */
1050     @Test
testNetworkSpecifierHandleUserSelectionConnectToNetwork()1051     public void testNetworkSpecifierHandleUserSelectionConnectToNetwork() throws Exception {
1052         sendNetworkRequestAndSetupForUserSelection();
1053 
1054         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1055                 mNetworkRequestUserSelectionCallback.getValue();
1056         assertNotNull(networkRequestUserSelectionCallback);
1057 
1058         // Now trigger user selection to one of the network.
1059         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
1060         mSelectedNetwork = WifiConfigurationTestUtil.createPskNetwork();
1061         mSelectedNetwork.SSID = "\"" + mTestScanDatas[0].getResults()[0].SSID + "\"";
1062         networkRequestUserSelectionCallback.select(mSelectedNetwork);
1063         mLooper.dispatchAll();
1064 
1065         // Cancel periodic scans.
1066         verify(mAlarmManager).cancel(any(OnAlarmListener.class));
1067         // Disable connectivity manager
1068         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(true);
1069 
1070         validateConnectParams(mSelectedNetwork.SSID, matchingScanResult.BSSID);
1071         verify(mWifiMetrics).setNominatorForNetwork(anyInt(),
1072                 eq(WifiMetricsProto.ConnectionEvent.NOMINATOR_SPECIFIER));
1073 
1074         verify(mClientModeImpl).disconnectCommand();
1075         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
1076         verify(mClientModeImpl).sendMessage(messageCaptor.capture());
1077 
1078         Message message = messageCaptor.getValue();
1079         assertNotNull(message);
1080 
1081         assertEquals(WifiManager.CONNECT_NETWORK, message.what);
1082         assertEquals(TEST_NETWORK_ID_1, message.arg1);
1083     }
1084 
1085     /**
1086      * Verify handling of user selection to trigger connection to an existing saved network.
1087      */
1088     @Test
testNetworkSpecifierHandleUserSelectionConnectToExistingSavedNetwork()1089     public void testNetworkSpecifierHandleUserSelectionConnectToExistingSavedNetwork()
1090             throws Exception {
1091         sendNetworkRequestAndSetupForUserSelection();
1092 
1093         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1094                 mNetworkRequestUserSelectionCallback.getValue();
1095         assertNotNull(networkRequestUserSelectionCallback);
1096 
1097         mSelectedNetwork = WifiConfigurationTestUtil.createPskNetwork();
1098         mSelectedNetwork.SSID = "\"" + mTestScanDatas[0].getResults()[0].SSID + "\"";
1099 
1100         // Have a saved network with the same configuration.
1101         WifiConfiguration matchingSavedNetwork = new WifiConfiguration(mSelectedNetwork);
1102         matchingSavedNetwork.networkId = TEST_NETWORK_ID_1;
1103         when(mWifiConfigManager.getConfiguredNetwork(mSelectedNetwork.configKey()))
1104                 .thenReturn(matchingSavedNetwork);
1105 
1106         // Now trigger user selection to one of the network.
1107         networkRequestUserSelectionCallback.select(mSelectedNetwork);
1108         mLooper.dispatchAll();
1109 
1110         // Cancel periodic scans.
1111         verify(mAlarmManager).cancel(any(OnAlarmListener.class));
1112         // Disable connectivity manager
1113         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(true);
1114 
1115         // verify we don't try to add the network to WifiConfigManager.
1116         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt(), anyString());
1117 
1118         verify(mClientModeImpl).disconnectCommand();
1119         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
1120         verify(mClientModeImpl).sendMessage(messageCaptor.capture());
1121 
1122         Message message = messageCaptor.getValue();
1123         assertNotNull(message);
1124 
1125         assertEquals(WifiManager.CONNECT_NETWORK, message.what);
1126         assertEquals(TEST_NETWORK_ID_1, message.arg1);
1127     }
1128 
1129     /**
1130      * Verify handling of user selection to trigger connection to a network. Ensure we fill
1131      * up the BSSID field.
1132      */
1133     @Test
1134     public void
testNetworkSpecifierHandleUserSelectionConnectToNetworkUsingLiteralSsidAndBssidMatch()1135             testNetworkSpecifierHandleUserSelectionConnectToNetworkUsingLiteralSsidAndBssidMatch()
1136             throws Exception {
1137         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
1138                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
1139 
1140         // Make a specific AP request.
1141         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
1142         PatternMatcher ssidPatternMatch =
1143                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
1144         Pair<MacAddress, MacAddress> bssidPatternMatch =
1145                 Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
1146                         MacAddress.BROADCAST_ADDRESS);
1147         WifiConfiguration wifiConfiguration = new WifiConfiguration();
1148         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
1149         wifiConfiguration.preSharedKey = TEST_WPA_PRESHARED_KEY;
1150         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
1151                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
1152                 TEST_PACKAGE_NAME_1);
1153         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
1154         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1155         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
1156                 TEST_CALLBACK_IDENTIFIER);
1157         verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
1158                 mNetworkRequestUserSelectionCallback.capture());
1159         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
1160 
1161         // Now trigger user selection to the network.
1162         mSelectedNetwork = ScanResultUtil.createNetworkFromScanResult(matchingScanResult);
1163         mSelectedNetwork.SSID = "\"" + matchingScanResult.SSID + "\"";
1164         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1165                 mNetworkRequestUserSelectionCallback.getValue();
1166         assertNotNull(networkRequestUserSelectionCallback);
1167         networkRequestUserSelectionCallback.select(mSelectedNetwork);
1168         mLooper.dispatchAll();
1169 
1170         // Verify WifiConfiguration params.
1171         validateConnectParams(mSelectedNetwork.SSID, matchingScanResult.BSSID);
1172         verify(mWifiMetrics).setNominatorForNetwork(anyInt(),
1173                 eq(WifiMetricsProto.ConnectionEvent.NOMINATOR_SPECIFIER));
1174 
1175         verify(mClientModeImpl).disconnectCommand();
1176         // Verify connection message.
1177         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
1178         verify(mClientModeImpl).sendMessage(messageCaptor.capture());
1179 
1180         Message message = messageCaptor.getValue();
1181         assertNotNull(message);
1182 
1183         assertEquals(WifiManager.CONNECT_NETWORK, message.what);
1184         assertEquals(TEST_NETWORK_ID_1, message.arg1);
1185     }
1186 
1187     /**
1188      * Verify handling of user selection to trigger connection to a network. Ensure we fill
1189      * up the BSSID field with scan result for highest RSSI.
1190      */
1191     @Test
1192     public void
testNetworkSpecifierHandleUserSelectionConnectToNetworkMultipleBssidMatches()1193             testNetworkSpecifierHandleUserSelectionConnectToNetworkMultipleBssidMatches()
1194             throws Exception {
1195         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
1196                 TEST_SSID_1, TEST_SSID_1, TEST_SSID_1, TEST_SSID_4);
1197 
1198         // Make a ssid pattern request which matches 3 scan results - 0, 1, 2.
1199         PatternMatcher ssidPatternMatch =
1200                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
1201         Pair<MacAddress, MacAddress> bssidPatternMatch =
1202                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
1203         WifiConfiguration wifiConfiguration = new WifiConfiguration();
1204         wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
1205         wifiConfiguration.preSharedKey = TEST_WPA_PRESHARED_KEY;
1206         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
1207                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
1208                 TEST_PACKAGE_NAME_1);
1209         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
1210         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1211         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
1212                 TEST_CALLBACK_IDENTIFIER);
1213         verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
1214                 mNetworkRequestUserSelectionCallback.capture());
1215         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
1216 
1217         // Scan result 2 has the highest RSSI, so that should be picked.
1218         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[2];
1219 
1220         // Now trigger user selection to the network.
1221         mSelectedNetwork = ScanResultUtil.createNetworkFromScanResult(matchingScanResult);
1222         mSelectedNetwork.SSID = "\"" + matchingScanResult.SSID + "\"";
1223         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1224                 mNetworkRequestUserSelectionCallback.getValue();
1225         assertNotNull(networkRequestUserSelectionCallback);
1226         networkRequestUserSelectionCallback.select(mSelectedNetwork);
1227         mLooper.dispatchAll();
1228 
1229         // Verify WifiConfiguration params.
1230         validateConnectParams(mSelectedNetwork.SSID, matchingScanResult.BSSID);
1231         verify(mWifiMetrics).setNominatorForNetwork(anyInt(),
1232                 eq(WifiMetricsProto.ConnectionEvent.NOMINATOR_SPECIFIER));
1233 
1234         verify(mClientModeImpl).disconnectCommand();
1235         // Verify connection message.
1236         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
1237         verify(mClientModeImpl).sendMessage(messageCaptor.capture());
1238 
1239         Message message = messageCaptor.getValue();
1240         assertNotNull(message);
1241 
1242         assertEquals(WifiManager.CONNECT_NETWORK, message.what);
1243         assertEquals(TEST_NETWORK_ID_1, message.arg1);
1244     }
1245 
1246     /**
1247      * Verify handling of user selection to reject the request.
1248      */
1249     @Test
testNetworkSpecifierHandleUserSelectionReject()1250     public void testNetworkSpecifierHandleUserSelectionReject() throws Exception {
1251         sendNetworkRequestAndSetupForUserSelection();
1252 
1253         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1254                 mNetworkRequestUserSelectionCallback.getValue();
1255         assertNotNull(networkRequestUserSelectionCallback);
1256 
1257         // Now trigger user rejection.
1258         networkRequestUserSelectionCallback.reject();
1259         mLooper.dispatchAll();
1260 
1261         // Cancel periodic scans.
1262         verify(mAlarmManager).cancel(any(OnAlarmListener.class));
1263         // Verify we reset the network request handling.
1264         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1265         verifyUnfullfillableDispatched(mConnectivityMessenger);
1266 
1267         verify(mWifiMetrics).incrementNetworkRequestApiNumUserReject();
1268 
1269         // Verify we did not attempt to trigger a connection.
1270         verifyNoMoreInteractions(mClientModeImpl, mWifiConfigManager);
1271     }
1272 
1273     /**
1274      * Verify handling of connection timeout.
1275      * The timeouts should trigger connection retries until we hit the max.
1276      */
1277     @Test
testNetworkSpecifierHandleConnectionTimeout()1278     public void testNetworkSpecifierHandleConnectionTimeout() throws Exception {
1279         sendNetworkRequestAndSetupForConnectionStatus();
1280 
1281         // Simulate connection timeout beyond the retry limit to trigger the failure handling.
1282         for (int i = 0; i <= WifiNetworkFactory.USER_SELECTED_NETWORK_CONNECT_RETRY_MAX; i++) {
1283             mConnectionTimeoutAlarmListenerArgumentCaptor.getValue().onAlarm();
1284             mLooper.dispatchAll();
1285         }
1286 
1287         mInOrder = inOrder(mAlarmManager, mClientModeImpl);
1288         validateConnectionRetryAttempts();
1289 
1290         // Fail the request after all the retries are exhausted.
1291         verify(mNetworkRequestMatchCallback).onAbort();
1292         // Verify that we sent the connection failure callback.
1293         verify(mNetworkRequestMatchCallback).onUserSelectionConnectFailure(
1294                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1295         // Verify we reset the network request handling.
1296         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1297         verifyUnfullfillableDispatched(mConnectivityMessenger);
1298     }
1299 
1300     /**
1301      * Verify handling of connection trigger failure.
1302      * The trigger failures should trigger connection retries until we hit the max.
1303      */
1304     @Test
testNetworkSpecifierHandleConnectionTriggerFailure()1305     public void testNetworkSpecifierHandleConnectionTriggerFailure() throws Exception {
1306         Messenger replyToMsgr = sendNetworkRequestAndSetupForConnectionStatus();
1307 
1308         // Send failure message beyond the retry limit to trigger the failure handling.
1309         for (int i = 0; i <= WifiNetworkFactory.USER_SELECTED_NETWORK_CONNECT_RETRY_MAX; i++) {
1310             Message failureMsg = Message.obtain();
1311             failureMsg.what = WifiManager.CONNECT_NETWORK_FAILED;
1312             replyToMsgr.send(failureMsg);
1313             mLooper.dispatchAll();
1314         }
1315 
1316         mInOrder = inOrder(mAlarmManager, mClientModeImpl);
1317         validateConnectionRetryAttempts();
1318 
1319         // Fail the request after all the retries are exhausted.
1320         verify(mNetworkRequestMatchCallback).onAbort();
1321         // Verify that we sent the connection failure callback.
1322         verify(mNetworkRequestMatchCallback).onUserSelectionConnectFailure(
1323                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1324         // verify we canceled the timeout alarm.
1325         mInOrder.verify(mAlarmManager).cancel(
1326                 mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1327         // Verify we reset the network request handling.
1328         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1329         verifyUnfullfillableDispatched(mConnectivityMessenger);
1330     }
1331 
1332     /**
1333      * Verify handling of connection failure.
1334      * The connection failures should trigger connection retries until we hit the max.
1335      */
1336     @Test
testNetworkSpecifierHandleConnectionFailure()1337     public void testNetworkSpecifierHandleConnectionFailure() throws Exception {
1338         sendNetworkRequestAndSetupForConnectionStatus();
1339 
1340         assertNotNull(mSelectedNetwork);
1341 
1342         // Send network connection failure indication beyond the retry limit to trigger the failure
1343         // handling.
1344         for (int i = 0; i <= WifiNetworkFactory.USER_SELECTED_NETWORK_CONNECT_RETRY_MAX; i++) {
1345             mWifiNetworkFactory.handleConnectionAttemptEnded(
1346                     WifiMetrics.ConnectionEvent.FAILURE_DHCP, mSelectedNetwork);
1347             mLooper.dispatchAll();
1348         }
1349 
1350         mInOrder = inOrder(mAlarmManager, mClientModeImpl);
1351         validateConnectionRetryAttempts();
1352 
1353         verify(mNetworkRequestMatchCallback).onAbort();
1354         // Verify that we sent the connection failure callback.
1355         verify(mNetworkRequestMatchCallback).onUserSelectionConnectFailure(
1356                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1357         // verify we canceled the timeout alarm.
1358         mInOrder.verify(mAlarmManager).cancel(
1359                 mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1360         // Verify we reset the network request handling.
1361         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1362         verifyUnfullfillableDispatched(mConnectivityMessenger);
1363     }
1364 
1365     /**
1366      * Verify handling of connection failure to a different network.
1367      */
1368     @Test
testNetworkSpecifierHandleConnectionFailureToWrongNetwork()1369     public void testNetworkSpecifierHandleConnectionFailureToWrongNetwork() throws Exception {
1370         sendNetworkRequestAndSetupForConnectionStatus();
1371 
1372         // Send network connection failure to a different network indication.
1373         assertNotNull(mSelectedNetwork);
1374         WifiConfiguration connectedNetwork = new WifiConfiguration(mSelectedNetwork);
1375         connectedNetwork.SSID += "test";
1376         mWifiNetworkFactory.handleConnectionAttemptEnded(
1377                 WifiMetrics.ConnectionEvent.FAILURE_DHCP, connectedNetwork);
1378 
1379         // Verify that we did not send the connection failure callback.
1380         verify(mNetworkRequestMatchCallback, never()).onUserSelectionConnectFailure(any());
1381         // verify we canceled the timeout alarm.
1382         verify(mAlarmManager, never())
1383                 .cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1384         // Verify we don't reset the network request handling.
1385         verify(mWifiConnectivityManager, never())
1386                 .setSpecificNetworkRequestInProgress(false);
1387 
1388         // Send network connection failure indication beyond the retry limit to trigger the failure
1389         // handling.
1390         for (int i = 0; i <= WifiNetworkFactory.USER_SELECTED_NETWORK_CONNECT_RETRY_MAX; i++) {
1391             mWifiNetworkFactory.handleConnectionAttemptEnded(
1392                     WifiMetrics.ConnectionEvent.FAILURE_DHCP, mSelectedNetwork);
1393             mLooper.dispatchAll();
1394         }
1395 
1396         mInOrder = inOrder(mAlarmManager, mClientModeImpl);
1397         validateConnectionRetryAttempts();
1398 
1399         // Verify that we sent the connection failure callback.
1400         verify(mNetworkRequestMatchCallback).onUserSelectionConnectFailure(
1401                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1402         // verify we canceled the timeout alarm.
1403         mInOrder.verify(mAlarmManager).cancel(
1404                 mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1405         // Verify we reset the network request handling.
1406         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1407         verifyUnfullfillableDispatched(mConnectivityMessenger);
1408     }
1409 
1410     /**
1411      * Verify handling of connection success.
1412      */
1413     @Test
testNetworkSpecifierHandleConnectionSuccess()1414     public void testNetworkSpecifierHandleConnectionSuccess() throws Exception {
1415         sendNetworkRequestAndSetupForConnectionStatus();
1416 
1417         // Send network connection success indication.
1418         assertNotNull(mSelectedNetwork);
1419         mWifiNetworkFactory.handleConnectionAttemptEnded(
1420                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1421 
1422         // Verify that we sent the connection success callback.
1423         verify(mNetworkRequestMatchCallback).onUserSelectionConnectSuccess(
1424                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1425         // verify we canceled the timeout alarm.
1426         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1427 
1428         verify(mWifiMetrics).incrementNetworkRequestApiNumConnectSuccess();
1429     }
1430 
1431     /**
1432      * Verify that we ignore connection success events after the first one (may be triggered by a
1433      * roam event)
1434      */
1435     @Test
testNetworkSpecifierDuplicateHandleConnectionSuccess()1436     public void testNetworkSpecifierDuplicateHandleConnectionSuccess() throws Exception {
1437         sendNetworkRequestAndSetupForConnectionStatus();
1438 
1439         // Send network connection success indication.
1440         assertNotNull(mSelectedNetwork);
1441         mWifiNetworkFactory.handleConnectionAttemptEnded(
1442                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1443 
1444         // Verify that we sent the connection success callback.
1445         verify(mNetworkRequestMatchCallback).onUserSelectionConnectSuccess(
1446                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1447         // verify we canceled the timeout alarm.
1448         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1449 
1450         verify(mWifiMetrics).incrementNetworkRequestApiNumConnectSuccess();
1451 
1452         // Send second network connection success indication which should be ignored.
1453         mWifiNetworkFactory.handleConnectionAttemptEnded(
1454                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1455         verifyNoMoreInteractions(mNetworkRequestMatchCallback);
1456     }
1457 
1458     /**
1459      * Verify that we ignore any connection failure events after the first connection success (may
1460      * be triggered by a disconnect).
1461      * Note: The disconnect handling will be done via the NetworkAgent.
1462      */
1463     @Test
testNetworkSpecifierHandleConnectionFailureAfterSuccess()1464     public void testNetworkSpecifierHandleConnectionFailureAfterSuccess() throws Exception {
1465         sendNetworkRequestAndSetupForConnectionStatus();
1466 
1467         // Send network connection success indication.
1468         assertNotNull(mSelectedNetwork);
1469         mWifiNetworkFactory.handleConnectionAttemptEnded(
1470                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1471 
1472         // Verify that we sent the connection success callback.
1473         verify(mNetworkRequestMatchCallback).onUserSelectionConnectSuccess(
1474                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1475         // verify we canceled the timeout alarm.
1476         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1477 
1478         verify(mWifiMetrics).incrementNetworkRequestApiNumConnectSuccess();
1479 
1480         // Send a network connection failure indication which should be ignored (beyond the retry
1481         // limit to trigger the failure handling).
1482         for (int i = 0; i <= WifiNetworkFactory.USER_SELECTED_NETWORK_CONNECT_RETRY_MAX; i++) {
1483             mWifiNetworkFactory.handleConnectionAttemptEnded(
1484                     WifiMetrics.ConnectionEvent.FAILURE_DHCP, mSelectedNetwork);
1485             mLooper.dispatchAll();
1486         }
1487         // Verify that we ignore the second connection failure callback.
1488         verifyNoMoreInteractions(mNetworkRequestMatchCallback);
1489     }
1490 
1491     /**
1492      * Verify handling of connection success to a different network.
1493      */
1494     @Test
testNetworkSpecifierHandleConnectionSuccessToWrongNetwork()1495     public void testNetworkSpecifierHandleConnectionSuccessToWrongNetwork() throws Exception {
1496         sendNetworkRequestAndSetupForConnectionStatus();
1497 
1498         // Send network connection success to a different network indication.
1499         assertNotNull(mSelectedNetwork);
1500         WifiConfiguration connectedNetwork = new WifiConfiguration(mSelectedNetwork);
1501         connectedNetwork.SSID += "test";
1502         mWifiNetworkFactory.handleConnectionAttemptEnded(
1503                 WifiMetrics.ConnectionEvent.FAILURE_NONE, connectedNetwork);
1504 
1505         // verify that we did not send out the success callback and did not stop the alarm timeout.
1506         verify(mNetworkRequestMatchCallback, never()).onUserSelectionConnectSuccess(any());
1507         verify(mAlarmManager, never())
1508                 .cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1509 
1510         // Send network connection success to the correct network indication.
1511         mWifiNetworkFactory.handleConnectionAttemptEnded(
1512                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1513 
1514         // Verify that we sent the connection success callback.
1515         verify(mNetworkRequestMatchCallback).onUserSelectionConnectSuccess(
1516                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1517         // verify we canceled the timeout alarm.
1518         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1519     }
1520 
1521     /**
1522      * Verify handling of request release after connecting to the network.
1523      */
1524     @Test
testHandleNetworkReleaseWithSpecifierAfterConnectionSuccess()1525     public void testHandleNetworkReleaseWithSpecifierAfterConnectionSuccess() throws Exception {
1526         sendNetworkRequestAndSetupForConnectionStatus();
1527 
1528         // Send network connection success indication.
1529         assertNotNull(mSelectedNetwork);
1530         mWifiNetworkFactory.handleConnectionAttemptEnded(
1531                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1532 
1533         // Verify that we sent the connection success callback.
1534         verify(mNetworkRequestMatchCallback).onUserSelectionConnectSuccess(
1535                 argThat(new WifiConfigMatcher(mSelectedNetwork)));
1536         // verify we canceled the timeout alarm.
1537         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1538 
1539         // Now release the network request.
1540         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1541         // Verify that we triggered a disconnect.
1542         verify(mClientModeImpl, times(2)).disconnectCommand();
1543         // Re-enable connectivity manager .
1544         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1545     }
1546 
1547     /**
1548      * Verify we return the correct UID when processing network request with network specifier.
1549      */
1550     @Test
testHandleNetworkRequestWithSpecifierGetUid()1551     public void testHandleNetworkRequestWithSpecifierGetUid() throws Exception {
1552         assertEquals(Integer.valueOf(Process.INVALID_UID),
1553                 mWifiNetworkFactory.getSpecificNetworkRequestUidAndPackageName(
1554                         new WifiConfiguration()).first);
1555         assertTrue(mWifiNetworkFactory.getSpecificNetworkRequestUidAndPackageName(
1556                         new WifiConfiguration()).second.isEmpty());
1557 
1558         sendNetworkRequestAndSetupForConnectionStatus();
1559         assertNotNull(mSelectedNetwork);
1560 
1561         // connected to a different network.
1562         WifiConfiguration connectedNetwork = new WifiConfiguration(mSelectedNetwork);
1563         connectedNetwork.SSID += "test";
1564         assertEquals(Integer.valueOf(Process.INVALID_UID),
1565                 mWifiNetworkFactory.getSpecificNetworkRequestUidAndPackageName(
1566                         new WifiConfiguration()).first);
1567         assertTrue(mWifiNetworkFactory.getSpecificNetworkRequestUidAndPackageName(
1568                 new WifiConfiguration()).second.isEmpty());
1569 
1570         // connected to the correct network.
1571         connectedNetwork = new WifiConfiguration(mSelectedNetwork);
1572         assertEquals(Integer.valueOf(TEST_UID_1),
1573                 mWifiNetworkFactory.getSpecificNetworkRequestUidAndPackageName(
1574                         connectedNetwork).first);
1575         assertEquals(TEST_PACKAGE_NAME_1,
1576                 mWifiNetworkFactory.getSpecificNetworkRequestUidAndPackageName(
1577                         connectedNetwork).second);
1578     }
1579 
1580     /**
1581      *  Verify handling for new network request while processing another one.
1582      */
1583     @Test
testHandleNewNetworkRequestWithSpecifierWhenScanning()1584     public void testHandleNewNetworkRequestWithSpecifierWhenScanning() throws Exception {
1585         WifiNetworkSpecifier specifier1 = createWifiNetworkSpecifier(TEST_UID_1, false);
1586         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1587         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1588 
1589         // Register callback.
1590         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
1591                 TEST_CALLBACK_IDENTIFIER);
1592         verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(any());
1593 
1594         // Send second request.
1595         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
1596         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1597         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1598         mLooper.dispatchAll();
1599 
1600         verify(mNetworkRequestMatchCallback).onAbort();
1601         verify(mWifiScanner, times(2)).startScan(any(), any(), any());
1602         verifyUnfullfillableDispatched(mConnectivityMessenger);
1603 
1604         // Remove the stale request1 & ensure nothing happens.
1605         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1606         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1607 
1608         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1609                 mAlarmManager, mNetworkRequestMatchCallback);
1610 
1611         // Remove the active request2 & ensure auto-join is re-enabled.
1612         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1613         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1614 
1615         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1616     }
1617 
1618     /**
1619      *  Verify handling for new network request while processing another one.
1620      */
1621     @Test
testHandleNewNetworkRequestWithSpecifierAfterMatch()1622     public void testHandleNewNetworkRequestWithSpecifierAfterMatch() throws Exception {
1623         sendNetworkRequestAndSetupForUserSelection();
1624         WifiNetworkSpecifier specifier1 =
1625                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1626 
1627         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
1628                 mNetworkRequestUserSelectionCallback.getValue();
1629         assertNotNull(networkRequestUserSelectionCallback);
1630 
1631         // Send second request.
1632         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
1633         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1634         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1635 
1636         // Ignore stale callbacks.
1637         WifiConfiguration selectedNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1638         networkRequestUserSelectionCallback.select(selectedNetwork);
1639         mLooper.dispatchAll();
1640 
1641         verify(mNetworkRequestMatchCallback).onAbort();
1642         verify(mWifiScanner, times(2)).startScan(any(), any(), any());
1643         verify(mAlarmManager).cancel(mPeriodicScanListenerArgumentCaptor.getValue());
1644         verifyUnfullfillableDispatched(mConnectivityMessenger);
1645 
1646         // Remove the stale request1 & ensure nothing happens.
1647         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1648         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1649 
1650         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1651                 mAlarmManager, mNetworkRequestMatchCallback);
1652 
1653         // Remove the active request2 & ensure auto-join is re-enabled.
1654         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1655         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1656 
1657         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1658     }
1659 
1660     /**
1661      *  Verify handling for new network request while processing another one.
1662      */
1663     @Test
testHandleNewNetworkRequestWithSpecifierAfterConnect()1664     public void testHandleNewNetworkRequestWithSpecifierAfterConnect() throws Exception {
1665         sendNetworkRequestAndSetupForConnectionStatus();
1666         WifiNetworkSpecifier specifier1 =
1667                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1668 
1669         // Send second request.
1670         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
1671         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1672         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1673 
1674         verify(mNetworkRequestMatchCallback).onAbort();
1675         verify(mWifiConnectivityManager, times(1)).setSpecificNetworkRequestInProgress(true);
1676         verify(mWifiScanner, times(2)).startScan(any(), any(), any());
1677         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1678 
1679         // Remove the stale request1 & ensure nothing happens.
1680         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1681         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1682 
1683         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1684                 mAlarmManager, mNetworkRequestMatchCallback);
1685 
1686         // Remove the active request2 & ensure auto-join is re-enabled.
1687         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1688         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1689 
1690         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1691     }
1692 
1693     /**
1694      *  Verify handling for new network request while processing another one.
1695      */
1696     @Test
testHandleNewNetworkRequestWithSpecifierAfterConnectionSuccess()1697     public void testHandleNewNetworkRequestWithSpecifierAfterConnectionSuccess() throws Exception {
1698         sendNetworkRequestAndSetupForConnectionStatus();
1699         WifiNetworkSpecifier specifier1 =
1700                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1701 
1702         // Send network connection success indication.
1703         assertNotNull(mSelectedNetwork);
1704         mWifiNetworkFactory.handleConnectionAttemptEnded(
1705                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1706         // Cancel the connection timeout.
1707         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1708 
1709         // Send second request.
1710         WifiNetworkSpecifier specifier2 = createWifiNetworkSpecifier(TEST_UID_2, false);
1711         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1712         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1713 
1714         verify(mWifiConnectivityManager, times(1)).setSpecificNetworkRequestInProgress(true);
1715         verify(mWifiScanner, times(2)).startScan(any(), any(), any());
1716         // we shouldn't disconnect until the user accepts the next request.
1717         verify(mClientModeImpl, times(1)).disconnectCommand();
1718 
1719         // Remove the connected request1 & ensure we disconnect.
1720         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1721         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1722         verify(mClientModeImpl, times(2)).disconnectCommand();
1723 
1724         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1725                 mAlarmManager);
1726 
1727         // Now remove the active request2 & ensure auto-join is re-enabled.
1728         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1729         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1730 
1731         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1732 
1733         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1734                 mAlarmManager);
1735     }
1736 
1737     /**
1738      *  Verify handling for new network request while processing another one.
1739      */
1740     @Test
testHandleNewNetworkRequestWithSpecifierWhichUserSelectedAfterConnectionSuccess()1741     public void testHandleNewNetworkRequestWithSpecifierWhichUserSelectedAfterConnectionSuccess()
1742             throws Exception {
1743         sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
1744         WifiNetworkSpecifier specifier1 =
1745                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1746 
1747         // Send network connection success indication.
1748         assertNotNull(mSelectedNetwork);
1749         mWifiNetworkFactory.handleConnectionAttemptEnded(
1750                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1751         // Cancel the connection timeout.
1752         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1753 
1754         // Send second request & we simulate the user selecting the request & connecting to it.
1755         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager);
1756         sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_2);
1757         WifiNetworkSpecifier specifier2 =
1758                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1759         assertNotNull(mSelectedNetwork);
1760         mWifiNetworkFactory.handleConnectionAttemptEnded(
1761                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1762         // Cancel the connection timeout.
1763         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1764 
1765         // We shouldn't explicitly disconnect, the new connection attempt will implicitly disconnect
1766         // from the connected network.
1767         verify(mClientModeImpl, times(2)).disconnectCommand();
1768 
1769         // Remove the stale request1 & ensure nothing happens (because it was replaced by the
1770         // second request)
1771         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1772         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1773 
1774         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1775                 mAlarmManager);
1776 
1777         // Now remove the rejected request2, ensure we disconnect & re-enable auto-join.
1778         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1779         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1780         verify(mClientModeImpl, times(3)).disconnectCommand();
1781         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1782 
1783         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1784                 mAlarmManager);
1785     }
1786 
1787     /**
1788      *  Verify handling for new network request while processing another one.
1789      */
1790     @Test
testHandleNewNetworkRequestWithSpecifierWhichUserRejectedAfterConnectionSuccess()1791     public void testHandleNewNetworkRequestWithSpecifierWhichUserRejectedAfterConnectionSuccess()
1792             throws Exception {
1793         sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
1794         WifiNetworkSpecifier specifier1 =
1795                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1796 
1797         // Send network connection success indication.
1798         assertNotNull(mSelectedNetwork);
1799         mWifiNetworkFactory.handleConnectionAttemptEnded(
1800                 WifiMetrics.ConnectionEvent.FAILURE_NONE, mSelectedNetwork);
1801         // Cancel the connection timeout.
1802         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1803 
1804         // Send second request & we simulate the user rejecting the request.
1805         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager);
1806         sendNetworkRequestAndSetupForUserSelection(TEST_SSID_2);
1807         WifiNetworkSpecifier specifier2 =
1808                 (WifiNetworkSpecifier) mNetworkRequest.networkCapabilities.getNetworkSpecifier();
1809         mNetworkRequestUserSelectionCallback.getValue().reject();
1810         mLooper.dispatchAll();
1811         // cancel periodic scans.
1812         verify(mAlarmManager).cancel(mPeriodicScanListenerArgumentCaptor.getValue());
1813 
1814         // we shouldn't disconnect/re-enable auto-join until the connected request is released.
1815         verify(mWifiConnectivityManager, never()).setSpecificNetworkRequestInProgress(false);
1816         verify(mClientModeImpl, times(1)).disconnectCommand();
1817 
1818         // Remove the connected request1 & ensure we disconnect & ensure auto-join is re-enabled.
1819         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1820         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1821         verify(mClientModeImpl, times(2)).disconnectCommand();
1822         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1823 
1824         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1825                 mAlarmManager);
1826 
1827         // Now remove the rejected request2 & ensure nothing happens
1828         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier2);
1829         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1830 
1831         verifyNoMoreInteractions(mWifiConnectivityManager, mWifiScanner, mClientModeImpl,
1832                 mAlarmManager);
1833     }
1834 
1835     /**
1836      * Verify handling of screen state changes while triggering periodic scans to find matching
1837      * networks.
1838      */
1839     @Test
testNetworkSpecifierHandleScreenStateChangedWhileScanning()1840     public void testNetworkSpecifierHandleScreenStateChangedWhileScanning() throws Exception {
1841         sendNetworkRequestAndSetupForUserSelection();
1842 
1843         // Turn off screen.
1844         mWifiNetworkFactory.handleScreenStateChanged(false);
1845 
1846         // 1. Cancel the scan timer.
1847         mInOrder.verify(mAlarmManager).cancel(
1848                 mPeriodicScanListenerArgumentCaptor.getValue());
1849         // 2. Simulate the scan results from an ongoing scan, ensure no more scans are scheduled.
1850         mScanListenerArgumentCaptor.getValue().onResults(mTestScanDatas);
1851 
1852         // Ensure no more interactions.
1853         mInOrder.verifyNoMoreInteractions();
1854 
1855         // Now, turn the screen on.
1856         mWifiNetworkFactory.handleScreenStateChanged(true);
1857 
1858         // Verify that we resumed periodic scanning.
1859         mInOrder.verify(mWifiScanner).startScan(any(), any(), any());
1860     }
1861 
1862     /**
1863      * Verify handling of screen state changes after the active network request was released.
1864      */
1865     @Test
testNetworkSpecifierHandleScreenStateChangedWithoutActiveRequest()1866     public void testNetworkSpecifierHandleScreenStateChangedWithoutActiveRequest()
1867             throws Exception {
1868         sendNetworkRequestAndSetupForUserSelection();
1869         // Now release the active network request.
1870         mWifiNetworkFactory.releaseNetworkFor(mNetworkRequest);
1871         // Cancel the scan timer on release.
1872         mInOrder.verify(mAlarmManager).cancel(
1873                 mPeriodicScanListenerArgumentCaptor.getValue());
1874 
1875         // Turn off screen.
1876         mWifiNetworkFactory.handleScreenStateChanged(false);
1877 
1878         // Now, turn the screen on.
1879         mWifiNetworkFactory.handleScreenStateChanged(true);
1880 
1881         // Ensure that we did not pause or resume scanning.
1882         mInOrder.verifyNoMoreInteractions();
1883     }
1884 
1885     /**
1886      * Verify handling of screen state changes after user selected a network to connect to.
1887      */
1888     @Test
testNetworkSpecifierHandleScreenStateChangedAfterUserSelection()1889     public void testNetworkSpecifierHandleScreenStateChangedAfterUserSelection() throws Exception {
1890         sendNetworkRequestAndSetupForConnectionStatus();
1891 
1892         // Turn off screen.
1893         mWifiNetworkFactory.handleScreenStateChanged(false);
1894 
1895         // Now, turn the screen on.
1896         mWifiNetworkFactory.handleScreenStateChanged(true);
1897 
1898         // Ensure that we did not pause or resume scanning.
1899         mInOrder.verifyNoMoreInteractions();
1900     }
1901 
1902     /**
1903      * Verify we don't accept specific network request when wifi is off.
1904      */
1905     @Test
testHandleAcceptNetworkRequestWithSpecifierWhenWifiOff()1906     public void testHandleAcceptNetworkRequestWithSpecifierWhenWifiOff() throws Exception {
1907         when(mActivityManager.getPackageImportance(TEST_PACKAGE_NAME_1))
1908                 .thenReturn(IMPORTANCE_FOREGROUND);
1909 
1910         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
1911         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
1912 
1913         // set wifi off.
1914         mWifiNetworkFactory.setWifiState(false);
1915         assertFalse(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
1916 
1917         // set wifi on.
1918         mWifiNetworkFactory.setWifiState(true);
1919         assertTrue(mWifiNetworkFactory.acceptRequest(mNetworkRequest, 0));
1920     }
1921 
1922     /**
1923      * Verify handling of new network request with network specifier when wifi is off.
1924      */
1925     @Test
testHandleNetworkRequestWithSpecifierWhenWifiOff()1926     public void testHandleNetworkRequestWithSpecifierWhenWifiOff() {
1927         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
1928         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
1929 
1930         // set wifi off
1931         mWifiNetworkFactory.setWifiState(false);
1932         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1933         verify(mWifiScanner, never()).startScan(any(), any(), any());
1934 
1935         // set wifi on
1936         mWifiNetworkFactory.setWifiState(true);
1937         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1938         verify(mWifiScanner).startScan(any(), any(), any());
1939     }
1940 
1941     /**
1942      *  Verify wifi toggle off when scanning.
1943      */
1944     @Test
testHandleNetworkRequestWithSpecifierWifiOffWhenScanning()1945     public void testHandleNetworkRequestWithSpecifierWifiOffWhenScanning() throws Exception {
1946         WifiNetworkSpecifier specifier1 = createWifiNetworkSpecifier(TEST_UID_1, false);
1947         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier1);
1948         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
1949 
1950         // Register callback.
1951         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
1952                 TEST_CALLBACK_IDENTIFIER);
1953         verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(any());
1954 
1955         verify(mWifiScanner).startScan(any(), any(), any());
1956 
1957         // toggle wifi off & verify we aborted ongoing request.
1958         mWifiNetworkFactory.setWifiState(false);
1959         verify(mNetworkRequestMatchCallback).onAbort();
1960         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1961     }
1962 
1963     /**
1964      *  Verify wifi toggle off after connection attempt is started.
1965      */
1966     @Test
testHandleNetworkRequestWithSpecifierWifiOffAfterConnect()1967     public void testHandleNetworkRequestWithSpecifierWifiOffAfterConnect() throws Exception {
1968         sendNetworkRequestAndSetupForConnectionStatus();
1969 
1970         // toggle wifi off & verify we aborted ongoing request.
1971         mWifiNetworkFactory.setWifiState(false);
1972         verify(mAlarmManager).cancel(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
1973         verify(mNetworkRequestMatchCallback).onAbort();
1974         verify(mWifiConnectivityManager).setSpecificNetworkRequestInProgress(false);
1975     }
1976 
1977     /**
1978      * Verify handling of new network request with network specifier when wifi is off & then on.
1979      * Note: Unlike the other unit tests, this test invokes the top level
1980      * {@link NetworkFactory#CMD_REQUEST_NETWORK} to simulate the full flow.
1981      */
1982     @Test
testFullHandleNetworkRequestWithSpecifierWhenWifiOff()1983     public void testFullHandleNetworkRequestWithSpecifierWhenWifiOff() {
1984         WifiNetworkSpecifier specifier = createWifiNetworkSpecifier(TEST_UID_1, false);
1985         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
1986 
1987         // set wifi off
1988         mWifiNetworkFactory.setWifiState(false);
1989         // Add the request, should do nothing.
1990         Message message = Message.obtain();
1991         message.what = CMD_REQUEST_NETWORK;
1992         message.obj = mNetworkRequest;
1993         mWifiNetworkFactory.sendMessage(message);
1994         mLooper.dispatchAll();
1995         verify(mWifiScanner, never()).startScan(any(), any(), any());
1996 
1997         // set wifi on
1998         mWifiNetworkFactory.setWifiState(true);
1999         mLooper.dispatchAll();
2000         // Should trigger a re-evaluation of existing requests and the pending request will be
2001         // processed now.
2002         verify(mWifiScanner).startScan(any(), any(), any());
2003     }
2004 
2005     /**
2006      * Verify the user approval bypass for a specific request for an access point that was already
2007      * approved previously.
2008      */
2009     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchPreviouslyApproved()2010     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchPreviouslyApproved()
2011             throws Exception {
2012         // 1. First request (no user approval bypass)
2013         sendNetworkRequestAndSetupForConnectionStatus();
2014 
2015         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
2016         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager, mClientModeImpl);
2017 
2018         // 2. Second request for the same access point (user approval bypass).
2019         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
2020         PatternMatcher ssidPatternMatch =
2021                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2022         Pair<MacAddress, MacAddress> bssidPatternMatch =
2023                 Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
2024                         MacAddress.BROADCAST_ADDRESS);
2025         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2026                 ssidPatternMatch, bssidPatternMatch,
2027                 WifiConfigurationTestUtil.createPskNetwork(), TEST_UID_1, TEST_PACKAGE_NAME_1);
2028         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2029         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2030         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2031                 TEST_CALLBACK_IDENTIFIER);
2032         // Trigger scan results & ensure we triggered a connect.
2033         verify(mWifiScanner).startScan(any(), mScanListenerArgumentCaptor.capture(), any());
2034         ScanListener scanListener = mScanListenerArgumentCaptor.getValue();
2035         assertNotNull(scanListener);
2036         scanListener.onResults(mTestScanDatas);
2037 
2038         // Verify we did not trigger the match callback.
2039         verify(mNetworkRequestMatchCallback, never()).onMatch(anyList());
2040         // Verify that we sent a connection attempt to ClientModeImpl
2041         verify(mClientModeImpl).sendMessage(any());
2042 
2043         verify(mWifiMetrics).incrementNetworkRequestApiNumUserApprovalBypass();
2044     }
2045 
2046     /**
2047      * Verify that we don't bypass user approval for a specific request for an access point that was
2048      * approved previously, but then the user forgot it sometime after.
2049      */
2050     @Test
2051     public void
testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchPreviouslyApprovedNForgot()2052             testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchPreviouslyApprovedNForgot()
2053             throws Exception {
2054         // 1. First request (no user approval bypass)
2055         sendNetworkRequestAndSetupForConnectionStatus();
2056 
2057         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
2058         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager, mClientModeImpl);
2059 
2060         // 2. Simulate user forgeting the network.
2061         when(mWifiConfigManager.wasEphemeralNetworkDeleted(
2062                 ScanResultUtil.createQuotedSSID(mTestScanDatas[0].getResults()[0].SSID)))
2063                 .thenReturn(true);
2064 
2065         // 3. Second request for the same access point (user approval bypass).
2066         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
2067         PatternMatcher ssidPatternMatch =
2068                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2069         Pair<MacAddress, MacAddress> bssidPatternMatch =
2070                 Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
2071                         MacAddress.BROADCAST_ADDRESS);
2072         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2073                 ssidPatternMatch, bssidPatternMatch,
2074                 WifiConfigurationTestUtil.createPskNetwork(), TEST_UID_1, TEST_PACKAGE_NAME_1);
2075         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2076         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2077         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2078                 TEST_CALLBACK_IDENTIFIER);
2079         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
2080         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
2081                 ArgumentCaptor.forClass(List.class);
2082         // Verify we triggered the match callback.
2083         matchedScanResultsCaptor = ArgumentCaptor.forClass(List.class);
2084         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
2085         assertNotNull(matchedScanResultsCaptor.getValue());
2086         validateScanResults(matchedScanResultsCaptor.getValue(), matchingScanResult);
2087         // Verify that we did not send a connection attempt to ClientModeImpl.
2088         verify(mClientModeImpl, never()).sendMessage(any());
2089     }
2090 
2091     /**
2092      * Verify that we don't bypass user approval for a specific request for an access point that was
2093      * not approved previously.
2094      */
2095     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchNotPreviouslyApproved()2096     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchNotPreviouslyApproved()
2097             throws Exception {
2098         // 1. First request (no user approval bypass)
2099         sendNetworkRequestAndSetupForConnectionStatus();
2100 
2101         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
2102         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager, mClientModeImpl);
2103 
2104         // 2. Second request for a different access point (but same network).
2105         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
2106                 TEST_SSID_1, TEST_SSID_1, TEST_SSID_3, TEST_SSID_4);
2107         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[1];
2108         PatternMatcher ssidPatternMatch =
2109                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2110         Pair<MacAddress, MacAddress> bssidPatternMatch =
2111                 Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
2112                         MacAddress.BROADCAST_ADDRESS);
2113         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2114                 ssidPatternMatch, bssidPatternMatch, WifiConfigurationTestUtil.createPskNetwork(),
2115                 TEST_UID_1, TEST_PACKAGE_NAME_1);
2116         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2117         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2118         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2119                 TEST_CALLBACK_IDENTIFIER);
2120         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
2121         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
2122                 ArgumentCaptor.forClass(List.class);
2123         // Verify we triggered the match callback.
2124         matchedScanResultsCaptor = ArgumentCaptor.forClass(List.class);
2125         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
2126         assertNotNull(matchedScanResultsCaptor.getValue());
2127         validateScanResults(matchedScanResultsCaptor.getValue(), matchingScanResult);
2128         // Verify that we did not send a connection attempt to ClientModeImpl.
2129         verify(mClientModeImpl, never()).sendMessage(any());
2130     }
2131 
2132     /**
2133      * Verify that we don't bypass user approval for a specific request for a network
2134      * (not access point) that was approved previously.
2135      */
2136     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidMatchPreviouslyApproved()2137     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidMatchPreviouslyApproved()
2138             throws Exception {
2139         // 1. First request (no user approval bypass)
2140         sendNetworkRequestAndSetupForConnectionStatus();
2141 
2142         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
2143         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager, mClientModeImpl);
2144 
2145         // 2. Second request for the same network (but not specific access point)
2146         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
2147         PatternMatcher ssidPatternMatch =
2148                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2149         // match-all.
2150         Pair<MacAddress, MacAddress> bssidPatternMatch =
2151                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
2152         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2153                 ssidPatternMatch, bssidPatternMatch, WifiConfigurationTestUtil.createPskNetwork(),
2154                 TEST_UID_1, TEST_PACKAGE_NAME_1);
2155         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2156         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2157         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2158                 TEST_CALLBACK_IDENTIFIER);
2159         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
2160         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
2161                 ArgumentCaptor.forClass(List.class);
2162         // Verify we triggered the match callback.
2163         matchedScanResultsCaptor = ArgumentCaptor.forClass(List.class);
2164         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
2165         assertNotNull(matchedScanResultsCaptor.getValue());
2166         validateScanResults(matchedScanResultsCaptor.getValue(), matchingScanResult);
2167         // Verify that we did not send a connection attempt to ClientModeImpl.
2168         verify(mClientModeImpl, never()).sendMessage(any());
2169     }
2170 
2171     /**
2172      * Verify the we don't bypass user approval for a specific request for an access point that was
2173      * already approved previously, but was then removed (app uninstalled, user deleted it from
2174      * notification, from tests, etc).
2175      */
2176     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchAfterApprovalsRemove()2177     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchAfterApprovalsRemove()
2178             throws Exception {
2179         // 1. First request (no user approval bypass)
2180         sendNetworkRequestAndSetupForConnectionStatus();
2181 
2182         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
2183         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager, mClientModeImpl);
2184 
2185         // 2. Remove all approvals for the app.
2186         mWifiNetworkFactory.removeUserApprovedAccessPointsForApp(TEST_PACKAGE_NAME_1);
2187 
2188         // 3. Second request for the same access point
2189         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
2190         PatternMatcher ssidPatternMatch =
2191                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2192         Pair<MacAddress, MacAddress> bssidPatternMatch =
2193                 Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
2194                         MacAddress.ALL_ZEROS_ADDRESS);
2195         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2196                 ssidPatternMatch, bssidPatternMatch, WifiConfigurationTestUtil.createPskNetwork(),
2197                 TEST_UID_1, TEST_PACKAGE_NAME_1);
2198         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2199         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2200         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2201                 TEST_CALLBACK_IDENTIFIER);
2202         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
2203         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
2204                 ArgumentCaptor.forClass(List.class);
2205         // Verify we triggered the match callback.
2206         matchedScanResultsCaptor = ArgumentCaptor.forClass(List.class);
2207         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
2208         assertNotNull(matchedScanResultsCaptor.getValue());
2209         validateScanResults(matchedScanResultsCaptor.getValue(), matchingScanResult);
2210         // Verify that we did not send a connection attempt to ClientModeImpl.
2211         verify(mClientModeImpl, never()).sendMessage(any());
2212     }
2213 
2214     /**
2215      * Verify the we don't bypass user approval for a specific request for an access point that was
2216      * already approved previously, but then the user perform network settings reset.
2217      */
2218     @Test
testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchAfterClear()2219     public void testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchAfterClear()
2220             throws Exception {
2221         // 1. First request (no user approval bypass)
2222         sendNetworkRequestAndSetupForConnectionStatus();
2223 
2224         mWifiNetworkFactory.removeCallback(TEST_CALLBACK_IDENTIFIER);
2225         reset(mNetworkRequestMatchCallback, mWifiScanner, mAlarmManager, mClientModeImpl);
2226 
2227         // 2. Remove all approvals.
2228         mWifiNetworkFactory.clear();
2229 
2230         // 3. Second request for the same access point
2231         ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
2232         PatternMatcher ssidPatternMatch =
2233                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2234         Pair<MacAddress, MacAddress> bssidPatternMatch =
2235                 Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
2236                         MacAddress.ALL_ZEROS_ADDRESS);
2237         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2238                 ssidPatternMatch, bssidPatternMatch, WifiConfigurationTestUtil.createPskNetwork(),
2239                 TEST_UID_1, TEST_PACKAGE_NAME_1);
2240         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2241         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2242         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2243                 TEST_CALLBACK_IDENTIFIER);
2244         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
2245         ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
2246                 ArgumentCaptor.forClass(List.class);
2247         // Verify we triggered the match callback.
2248         matchedScanResultsCaptor = ArgumentCaptor.forClass(List.class);
2249         verify(mNetworkRequestMatchCallback).onMatch(matchedScanResultsCaptor.capture());
2250         assertNotNull(matchedScanResultsCaptor.getValue());
2251         validateScanResults(matchedScanResultsCaptor.getValue(), matchingScanResult);
2252         // Verify that we did not send a connection attempt to ClientModeImpl.
2253         verify(mClientModeImpl, never()).sendMessage(any());
2254     }
2255 
2256     /**
2257      * Verify the config store save for store user approval.
2258      */
2259     @Test
testNetworkSpecifierUserApprovalConfigStoreSave()2260     public void testNetworkSpecifierUserApprovalConfigStoreSave()
2261             throws Exception {
2262         sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
2263 
2264         // Verify config store interactions.
2265         verify(mWifiConfigManager).saveToStore(true);
2266         assertTrue(mDataSource.hasNewDataToSerialize());
2267 
2268         Map<String, Set<AccessPoint>> approvedAccessPointsMapToWrite = mDataSource.toSerialize();
2269         assertEquals(1, approvedAccessPointsMapToWrite.size());
2270         assertTrue(approvedAccessPointsMapToWrite.keySet().contains(TEST_PACKAGE_NAME_1));
2271         Set<AccessPoint> approvedAccessPointsToWrite =
2272                 approvedAccessPointsMapToWrite.get(TEST_PACKAGE_NAME_1);
2273         Set<AccessPoint> expectedApprovedAccessPoints =
2274                 new HashSet<AccessPoint>() {{
2275                     add(new AccessPoint(TEST_SSID_1, MacAddress.fromString(TEST_BSSID_1),
2276                             WifiConfiguration.SECURITY_TYPE_PSK));
2277                 }};
2278         assertEquals(expectedApprovedAccessPoints, approvedAccessPointsToWrite);
2279         // Ensure that the new data flag has been reset after read.
2280         assertFalse(mDataSource.hasNewDataToSerialize());
2281     }
2282 
2283     /**
2284      * Verify the config store load for store user approval.
2285      */
2286     @Test
testNetworkSpecifierUserApprovalConfigStoreLoad()2287     public void testNetworkSpecifierUserApprovalConfigStoreLoad()
2288             throws Exception {
2289         Map<String, Set<AccessPoint>> approvedAccessPointsMapToRead = new HashMap<>();
2290         Set<AccessPoint> approvedAccessPoints =
2291                 new HashSet<AccessPoint>() {{
2292                     add(new AccessPoint(TEST_SSID_1, MacAddress.fromString(TEST_BSSID_1),
2293                             WifiConfiguration.SECURITY_TYPE_PSK));
2294                 }};
2295         approvedAccessPointsMapToRead.put(TEST_PACKAGE_NAME_1, approvedAccessPoints);
2296         mDataSource.fromDeserialized(approvedAccessPointsMapToRead);
2297 
2298         // The new network request should bypass user approval for the same access point.
2299         PatternMatcher ssidPatternMatch =
2300                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2301         Pair<MacAddress, MacAddress> bssidPatternMatch =
2302                 Pair.create(MacAddress.fromString(TEST_BSSID_1),
2303                         MacAddress.BROADCAST_ADDRESS);
2304         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2305                 ssidPatternMatch, bssidPatternMatch, WifiConfigurationTestUtil.createPskNetwork(),
2306                 TEST_UID_1, TEST_PACKAGE_NAME_1);
2307         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2308         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2309         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2310                 TEST_CALLBACK_IDENTIFIER);
2311         // Trigger scan results & ensure we triggered a connect.
2312         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
2313                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
2314         verify(mWifiScanner).startScan(any(), mScanListenerArgumentCaptor.capture(), any());
2315         ScanListener scanListener = mScanListenerArgumentCaptor.getValue();
2316         assertNotNull(scanListener);
2317         scanListener.onResults(mTestScanDatas);
2318 
2319         // Verify we did not trigger the match callback.
2320         verify(mNetworkRequestMatchCallback, never()).onMatch(anyList());
2321         // Verify that we sent a connection attempt to ClientModeImpl
2322         verify(mClientModeImpl).sendMessage(any());
2323     }
2324 
sendNetworkRequestAndSetupForConnectionStatus()2325     private Messenger sendNetworkRequestAndSetupForConnectionStatus() throws RemoteException {
2326         return sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
2327     }
2328 
2329     // Helper method to setup the necessary pre-requisite steps for tracking connection status.
sendNetworkRequestAndSetupForConnectionStatus(String targetSsid)2330     private Messenger sendNetworkRequestAndSetupForConnectionStatus(String targetSsid)
2331             throws RemoteException {
2332         when(mClock.getElapsedSinceBootMillis()).thenReturn(0L);
2333 
2334         sendNetworkRequestAndSetupForUserSelection(targetSsid);
2335 
2336         INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
2337                 mNetworkRequestUserSelectionCallback.getValue();
2338         assertNotNull(networkRequestUserSelectionCallback);
2339 
2340         // Now trigger user selection to one of the network.
2341         mSelectedNetwork = WifiConfigurationTestUtil.createPskNetwork();
2342         mSelectedNetwork.SSID = "\"" + targetSsid + "\"";
2343         networkRequestUserSelectionCallback.select(mSelectedNetwork);
2344         mLooper.dispatchAll();
2345 
2346         // Cancel the periodic scan timer.
2347         mInOrder.verify(mAlarmManager).cancel(mPeriodicScanListenerArgumentCaptor.getValue());
2348         // Disable connectivity manager
2349         verify(mWifiConnectivityManager, atLeastOnce()).setSpecificNetworkRequestInProgress(true);
2350         // Increment the number of unique apps.
2351         verify(mWifiMetrics).incrementNetworkRequestApiNumApps();
2352 
2353         verify(mClientModeImpl, atLeastOnce()).disconnectCommand();
2354         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
2355         verify(mClientModeImpl, atLeastOnce()).sendMessage(messageCaptor.capture());
2356 
2357         Message message = messageCaptor.getValue();
2358         assertNotNull(message);
2359 
2360         // Start the connection timeout alarm.
2361         mInOrder.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
2362                 eq((long) WifiNetworkFactory.NETWORK_CONNECTION_TIMEOUT_MS), any(),
2363                 mConnectionTimeoutAlarmListenerArgumentCaptor.capture(), any());
2364         assertNotNull(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
2365 
2366         return message.replyTo;
2367     }
2368 
sendNetworkRequestAndSetupForUserSelection()2369     private void sendNetworkRequestAndSetupForUserSelection() throws RemoteException {
2370         sendNetworkRequestAndSetupForUserSelection(TEST_SSID_1);
2371     }
2372 
2373     // Helper method to setup the necessary pre-requisite steps for user selection.
sendNetworkRequestAndSetupForUserSelection(String targetSsid)2374     private void sendNetworkRequestAndSetupForUserSelection(String targetSsid)
2375             throws RemoteException {
2376         // Setup scan data for WPA-PSK networks.
2377         setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
2378                 TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
2379 
2380         // Setup network specifier for WPA-PSK networks.
2381         PatternMatcher ssidPatternMatch =
2382                 new PatternMatcher(targetSsid, PatternMatcher.PATTERN_LITERAL);
2383         Pair<MacAddress, MacAddress> bssidPatternMatch =
2384                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
2385         WifiConfiguration wifiConfiguration = WifiConfigurationTestUtil.createPskNetwork();
2386         wifiConfiguration.preSharedKey = TEST_WPA_PRESHARED_KEY;
2387         WifiNetworkSpecifier specifier = new WifiNetworkSpecifier(
2388                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, TEST_UID_1,
2389                 TEST_PACKAGE_NAME_1);
2390 
2391         mNetworkRequest.networkCapabilities.setNetworkSpecifier(specifier);
2392         mWifiNetworkFactory.needNetworkFor(mNetworkRequest, 0);
2393 
2394         mWifiNetworkFactory.addCallback(mAppBinder, mNetworkRequestMatchCallback,
2395                 TEST_CALLBACK_IDENTIFIER);
2396         verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
2397                 mNetworkRequestUserSelectionCallback.capture());
2398 
2399         verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
2400 
2401         verify(mNetworkRequestMatchCallback).onMatch(anyList());
2402     }
2403 
2404     // Simulates the periodic scans performed to find a matching network.
2405     // a) Start scan
2406     // b) Scan results received.
2407     // c) Set alarm for next scan at the expected interval.
2408     // d) Alarm fires, go to step a) again and repeat.
verifyPeriodicScans(long...expectedIntervalsInSeconds)2409     private void verifyPeriodicScans(long...expectedIntervalsInSeconds) {
2410         when(mClock.getElapsedSinceBootMillis()).thenReturn(0L);
2411 
2412         OnAlarmListener alarmListener = null;
2413         ScanListener scanListener = null;
2414 
2415         mInOrder = inOrder(mWifiScanner, mAlarmManager);
2416         for (int i = 0; i < expectedIntervalsInSeconds.length - 1; i++) {
2417             long expectedCurrentIntervalInMs = expectedIntervalsInSeconds[i];
2418             long expectedNextIntervalInMs = expectedIntervalsInSeconds[i + 1];
2419 
2420             // First scan is immediately fired, so need for the alarm to fire.
2421             if (expectedCurrentIntervalInMs != 0) {
2422                 // Fire the alarm and ensure that we started the next scan.
2423                 alarmListener.onAlarm();
2424             }
2425             mInOrder.verify(mWifiScanner).startScan(
2426                     any(), mScanListenerArgumentCaptor.capture(), any());
2427             scanListener = mScanListenerArgumentCaptor.getValue();
2428             assertNotNull(scanListener);
2429 
2430             // Now trigger the scan results callback and verify the alarm set for the next scan.
2431             scanListener.onResults(mTestScanDatas);
2432 
2433             mInOrder.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
2434                     eq(expectedNextIntervalInMs), any(),
2435                     mPeriodicScanListenerArgumentCaptor.capture(), any());
2436             alarmListener = mPeriodicScanListenerArgumentCaptor.getValue();
2437             assertNotNull(alarmListener);
2438         }
2439 
2440         mInOrder.verifyNoMoreInteractions();
2441     }
2442 
createWifiNetworkSpecifier(int uid, boolean isHidden)2443     private WifiNetworkSpecifier createWifiNetworkSpecifier(int uid, boolean isHidden) {
2444         PatternMatcher ssidPatternMatch =
2445                 new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
2446         Pair<MacAddress, MacAddress> bssidPatternMatch =
2447                 Pair.create(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
2448         WifiConfiguration wifiConfiguration;
2449         if (isHidden) {
2450             wifiConfiguration = WifiConfigurationTestUtil.createPskHiddenNetwork();
2451         } else {
2452             wifiConfiguration = WifiConfigurationTestUtil.createPskNetwork();
2453         }
2454         String packageName = null;
2455         if (uid == TEST_UID_1) {
2456             packageName = TEST_PACKAGE_NAME_1;
2457         } else if (uid == TEST_UID_2) {
2458             packageName = TEST_PACKAGE_NAME_2;
2459         } else {
2460             fail();
2461         }
2462         return new WifiNetworkSpecifier(
2463                 ssidPatternMatch, bssidPatternMatch, wifiConfiguration, uid, packageName);
2464     }
2465 
2466     private static final int SCAN_RESULT_TYPE_OPEN = 0;
2467     private static final int SCAN_RESULT_TYPE_WPA_PSK = 1;
2468     private static final int SCAN_RESULT_TYPE_WPA_EAP = 2;
2469 
getScanResultCapsForType(int scanResultType)2470     private String getScanResultCapsForType(int scanResultType) {
2471         switch (scanResultType) {
2472             case SCAN_RESULT_TYPE_OPEN:
2473                 return WifiConfigurationTestUtil.getScanResultCapsForNetwork(
2474                         WifiConfigurationTestUtil.createOpenNetwork());
2475             case SCAN_RESULT_TYPE_WPA_PSK:
2476                 return WifiConfigurationTestUtil.getScanResultCapsForNetwork(
2477                         WifiConfigurationTestUtil.createPskNetwork());
2478             case SCAN_RESULT_TYPE_WPA_EAP:
2479                 return WifiConfigurationTestUtil.getScanResultCapsForNetwork(
2480                         WifiConfigurationTestUtil.createEapNetwork());
2481         }
2482         fail("Invalid scan result type " + scanResultType);
2483         return "";
2484     }
2485 
2486     // Helper method to setup the scan data for verifying the matching algo.
setupScanData(int scanResultType, String ssid1, String ssid2, String ssid3, String ssid4)2487     private void setupScanData(int scanResultType, String ssid1, String ssid2, String ssid3,
2488             String ssid4) {
2489         // 4 scan results,
2490         assertEquals(1, mTestScanDatas.length);
2491         ScanResult[] scanResults = mTestScanDatas[0].getResults();
2492         assertEquals(4, scanResults.length);
2493 
2494         String caps = getScanResultCapsForType(scanResultType);
2495 
2496         // Scan results have increasing RSSI.
2497         scanResults[0].SSID = ssid1;
2498         scanResults[0].BSSID = TEST_BSSID_1;
2499         scanResults[0].capabilities = caps;
2500         scanResults[0].level = -45;
2501         scanResults[1].SSID = ssid2;
2502         scanResults[1].BSSID = TEST_BSSID_2;
2503         scanResults[1].capabilities = caps;
2504         scanResults[1].level = -35;
2505         scanResults[2].SSID = ssid3;
2506         scanResults[2].BSSID = TEST_BSSID_3;
2507         scanResults[2].capabilities = caps;
2508         scanResults[2].level = -25;
2509         scanResults[3].SSID = ssid4;
2510         scanResults[3].BSSID = TEST_BSSID_4;
2511         scanResults[3].capabilities = caps;
2512         scanResults[3].level = -15;
2513     }
2514 
validateScanResults( List<ScanResult> actualScanResults, ScanResult...expectedScanResults)2515     private void validateScanResults(
2516             List<ScanResult> actualScanResults, ScanResult...expectedScanResults) {
2517         assertEquals(expectedScanResults.length, actualScanResults.size());
2518         for (int i = 0; i < expectedScanResults.length; i++) {
2519             ScanResult expectedScanResult = expectedScanResults[i];
2520             ScanResult actualScanResult = actualScanResults.stream()
2521                     .filter(x -> x.BSSID.equals(expectedScanResult.BSSID))
2522                     .findFirst()
2523                     .orElse(null);
2524             ScanTestUtil.assertScanResultEquals(expectedScanResult, actualScanResult);
2525         }
2526     }
2527 
validateConnectionRetryAttempts()2528     private void validateConnectionRetryAttempts() {
2529         for (int i = 0; i < WifiNetworkFactory.USER_SELECTED_NETWORK_CONNECT_RETRY_MAX; i++) {
2530             // Cancel the existing connection timeout.
2531             mInOrder.verify(mAlarmManager).cancel(
2532                     mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
2533 
2534             // Trigger new connection.
2535             ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
2536             mInOrder.verify(mClientModeImpl).sendMessage(messageCaptor.capture());
2537             Message message = messageCaptor.getValue();
2538             assertNotNull(message);
2539             assertEquals(WifiManager.CONNECT_NETWORK, message.what);
2540 
2541             // Start the new connection timeout alarm.
2542             mInOrder.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
2543                     eq((long) WifiNetworkFactory.NETWORK_CONNECTION_TIMEOUT_MS), any(),
2544                     mConnectionTimeoutAlarmListenerArgumentCaptor.capture(), any());
2545             assertNotNull(mConnectionTimeoutAlarmListenerArgumentCaptor.getValue());
2546         }
2547     }
2548 
validateScanSettings(@ullable String hiddenSsid)2549     private void validateScanSettings(@Nullable String hiddenSsid) {
2550         ScanSettings scanSettings = mScanSettingsArgumentCaptor.getValue();
2551         assertNotNull(scanSettings);
2552         assertEquals(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, scanSettings.band);
2553         assertEquals(WifiScanner.TYPE_HIGH_ACCURACY, scanSettings.type);
2554         assertEquals(WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN, scanSettings.reportEvents);
2555         if (hiddenSsid == null) {
2556             assertNull(scanSettings.hiddenNetworks);
2557         } else {
2558             assertNotNull(scanSettings.hiddenNetworks);
2559             assertNotNull(scanSettings.hiddenNetworks[0]);
2560             assertEquals(scanSettings.hiddenNetworks[0].ssid, addEnclosingQuotes(hiddenSsid));
2561         }
2562         WorkSource workSource = mWorkSourceArgumentCaptor.getValue();
2563         assertNotNull(workSource);
2564         assertEquals(TEST_UID_1, workSource.get(0));
2565     }
2566 
2567     class WifiConfigMatcher implements ArgumentMatcher<WifiConfiguration> {
2568         private final WifiConfiguration mConfig;
2569 
WifiConfigMatcher(WifiConfiguration config)2570         WifiConfigMatcher(WifiConfiguration config) {
2571             assertNotNull(config);
2572             mConfig = config;
2573         }
2574 
2575         @Override
matches(WifiConfiguration otherConfig)2576         public boolean matches(WifiConfiguration otherConfig) {
2577             if (otherConfig == null) return false;
2578             return mConfig.configKey().equals(otherConfig.configKey());
2579         }
2580     }
2581 
2582     /**
2583      * Verify that an EVENT_UNFULFILLABLE_REQUEST was dispatched on the (mock) messenger.
2584      */
verifyUnfullfillableDispatched(Messenger messenger)2585     private void verifyUnfullfillableDispatched(Messenger messenger) throws Exception {
2586         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
2587         verify(messenger, atLeastOnce()).send(messageCaptor.capture());
2588         assertEquals(NetworkFactory.EVENT_UNFULFILLABLE_REQUEST, messageCaptor.getValue().what);
2589     }
2590 
validateUiStartParams(boolean expectedIsReqForSingeNetwork)2591     private void validateUiStartParams(boolean expectedIsReqForSingeNetwork) {
2592         ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
2593         verify(mContext).startActivityAsUser(
2594                 intentArgumentCaptor.capture(), eq(UserHandle.getUserHandleForUid(TEST_UID_1)));
2595         Intent intent = intentArgumentCaptor.getValue();
2596         assertNotNull(intent);
2597         assertEquals(intent.getAction(), WifiNetworkFactory.UI_START_INTENT_ACTION);
2598         assertTrue(intent.getCategories().contains(WifiNetworkFactory.UI_START_INTENT_CATEGORY));
2599         assertEquals(intent.getStringExtra(WifiNetworkFactory.UI_START_INTENT_EXTRA_APP_NAME),
2600                 TEST_APP_NAME);
2601         assertEquals(expectedIsReqForSingeNetwork, intent.getBooleanExtra(
2602                 WifiNetworkFactory.UI_START_INTENT_EXTRA_REQUEST_IS_FOR_SINGLE_NETWORK, false));
2603         assertTrue((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0);
2604         assertTrue((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0);
2605     }
2606 
validateConnectParams(String ssid, String bssid)2607     private void validateConnectParams(String ssid, String bssid) {
2608         ArgumentCaptor<WifiConfiguration> wifiConfigurationCaptor =
2609                 ArgumentCaptor.forClass(WifiConfiguration.class);
2610         verify(mWifiConfigManager).addOrUpdateNetwork(
2611                 wifiConfigurationCaptor.capture(), eq(TEST_UID_1), eq(TEST_PACKAGE_NAME_1));
2612         WifiConfiguration network =  wifiConfigurationCaptor.getValue();
2613         assertNotNull(network);
2614         WifiConfiguration expectedWifiConfiguration =
2615                 new WifiConfiguration(((WifiNetworkSpecifier) mNetworkRequest.networkCapabilities
2616                         .getNetworkSpecifier()).wifiConfiguration);
2617         expectedWifiConfiguration.SSID = ssid;
2618         expectedWifiConfiguration.preSharedKey = TEST_WPA_PRESHARED_KEY;
2619         expectedWifiConfiguration.BSSID = bssid;
2620         expectedWifiConfiguration.ephemeral = true;
2621         expectedWifiConfiguration.fromWifiNetworkSpecifier = true;
2622         WifiConfigurationTestUtil.assertConfigurationEqual(expectedWifiConfiguration, network);
2623     }
2624 }
2625