• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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.telephony.CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL;
20 import static android.telephony.TelephonyManager.DATA_ENABLED_REASON_CARRIER;
21 import static android.telephony.TelephonyManager.DATA_ENABLED_REASON_THERMAL;
22 import static android.telephony.TelephonyManager.DATA_ENABLED_REASON_USER;
23 
24 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
25 import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
26 import static com.android.server.wifi.WifiCarrierInfoManager.NOTIFICATION_USER_ALLOWED_CARRIER_INTENT_ACTION;
27 import static com.android.server.wifi.WifiCarrierInfoManager.NOTIFICATION_USER_CLICKED_INTENT_ACTION;
28 import static com.android.server.wifi.WifiCarrierInfoManager.NOTIFICATION_USER_DISALLOWED_CARRIER_INTENT_ACTION;
29 import static com.android.server.wifi.WifiCarrierInfoManager.NOTIFICATION_USER_DISMISSED_INTENT_ACTION;
30 
31 import static com.google.common.truth.Truth.assertThat;
32 
33 import static org.junit.Assert.assertEquals;
34 import static org.junit.Assert.assertFalse;
35 import static org.junit.Assert.assertNotNull;
36 import static org.junit.Assert.assertNull;
37 import static org.junit.Assert.assertTrue;
38 import static org.junit.Assume.assumeTrue;
39 import static org.mockito.Mockito.any;
40 import static org.mockito.Mockito.anyBoolean;
41 import static org.mockito.Mockito.anyInt;
42 import static org.mockito.Mockito.anyLong;
43 import static org.mockito.Mockito.anyString;
44 import static org.mockito.Mockito.atLeastOnce;
45 import static org.mockito.Mockito.atMost;
46 import static org.mockito.Mockito.eq;
47 import static org.mockito.Mockito.inOrder;
48 import static org.mockito.Mockito.lenient;
49 import static org.mockito.Mockito.mock;
50 import static org.mockito.Mockito.never;
51 import static org.mockito.Mockito.reset;
52 import static org.mockito.Mockito.spy;
53 import static org.mockito.Mockito.times;
54 import static org.mockito.Mockito.verify;
55 import static org.mockito.Mockito.verifyNoMoreInteractions;
56 
57 import android.app.Notification;
58 import android.app.PendingIntent;
59 import android.content.BroadcastReceiver;
60 import android.content.Intent;
61 import android.content.IntentFilter;
62 import android.content.pm.PackageInfo;
63 import android.content.pm.PackageManager;
64 import android.content.res.Resources;
65 import android.database.ContentObserver;
66 import android.net.Uri;
67 import android.net.wifi.WifiConfiguration;
68 import android.net.wifi.WifiContext;
69 import android.net.wifi.WifiEnterpriseConfig;
70 import android.net.wifi.WifiInfo;
71 import android.net.wifi.WifiManager;
72 import android.net.wifi.WifiStringResourceWrapper;
73 import android.net.wifi.hotspot2.PasspointConfiguration;
74 import android.net.wifi.hotspot2.pps.Credential;
75 import android.os.Handler;
76 import android.os.ParcelUuid;
77 import android.os.PersistableBundle;
78 import android.os.UserHandle;
79 import android.os.test.TestLooper;
80 import android.telephony.CarrierConfigManager;
81 import android.telephony.ImsiEncryptionInfo;
82 import android.telephony.SubscriptionInfo;
83 import android.telephony.SubscriptionManager;
84 import android.telephony.TelephonyManager;
85 import android.util.Base64;
86 import android.util.Pair;
87 
88 import androidx.test.filters.SmallTest;
89 
90 import com.android.dx.mockito.inline.extended.ExtendedMockito;
91 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
92 import com.android.modules.utils.build.SdkLevel;
93 import com.android.server.wifi.WifiCarrierInfoManager.SimAuthRequestData;
94 import com.android.server.wifi.WifiCarrierInfoManager.SimAuthResponseData;
95 import com.android.server.wifi.entitlement.PseudonymInfo;
96 import com.android.wifi.resources.R;
97 
98 import org.junit.After;
99 import org.junit.Before;
100 import org.junit.Test;
101 import org.mockito.ArgumentCaptor;
102 import org.mockito.InOrder;
103 import org.mockito.Mock;
104 import org.mockito.MockitoAnnotations;
105 import org.mockito.MockitoSession;
106 import org.mockito.quality.Strictness;
107 
108 import java.security.PublicKey;
109 import java.util.ArrayList;
110 import java.util.Arrays;
111 import java.util.Collections;
112 import java.util.HashMap;
113 import java.util.List;
114 import java.util.Optional;
115 import java.util.Set;
116 import java.util.function.Consumer;
117 
118 import javax.crypto.BadPaddingException;
119 import javax.crypto.Cipher;
120 
121 /**
122  * Unit tests for {@link WifiCarrierInfoManager}.
123  */
124 @SmallTest
125 public class WifiCarrierInfoManagerTest extends WifiBaseTest {
126     private WifiCarrierInfoManager mWifiCarrierInfoManager;
127 
128     private static final int DATA_SUBID = 1;
129     private static final int NON_DATA_SUBID = 2;
130     private static final int INVALID_SUBID = -1;
131     private static final int DATA_CARRIER_ID = 10;
132     private static final int PARENT_DATA_CARRIER_ID = 11;
133     private static final int NON_DATA_CARRIER_ID = 20;
134     private static final int PARENT_NON_DATA_CARRIER_ID = 21;
135     private static final int DEACTIVE_CARRIER_ID = 30;
136     private static final String MATCH_PREFIX_IMSI = "123456*";
137     private static final String DATA_FULL_IMSI = "123456789123456";
138     private static final String NON_DATA_FULL_IMSI = "123456987654321";
139     private static final String NO_MATCH_FULL_IMSI = "654321123456789";
140     private static final String NO_MATCH_PREFIX_IMSI = "654321*";
141     private static final String DATA_OPERATOR_NUMERIC = "123456";
142     private static final String NON_DATA_OPERATOR_NUMERIC = "123456";
143     private static final String NO_MATCH_OPERATOR_NUMERIC = "654321";
144     private static final String TEST_PACKAGE = "com.test12345";
145     private static final String ANONYMOUS_IDENTITY = "anonymous@wlan.mnc456.mcc123.3gppnetwork.org";
146     private static final String CARRIER_NAME = "Google";
147     private static final ParcelUuid GROUP_UUID = ParcelUuid
148             .fromString("0000110B-0000-1000-8000-00805F9B34FB");
149 
150     @Mock CarrierConfigManager mCarrierConfigManager;
151     @Mock WifiContext mContext;
152     @Mock Resources mResources;
153     @Mock FrameworkFacade mFrameworkFacade;
154     @Mock TelephonyManager mTelephonyManager;
155     @Mock TelephonyManager mDataTelephonyManager;
156     @Mock TelephonyManager mNonDataTelephonyManager;
157     @Mock SubscriptionManager mSubscriptionManager;
158     @Mock SubscriptionInfo mDataSubscriptionInfo;
159     @Mock SubscriptionInfo mNonDataSubscriptionInfo;
160     @Mock WifiConfigStore mWifiConfigStore;
161     @Mock WifiInjector mWifiInjector;
162     @Mock WifiNetworkFactory mWifiNetworkFactory;
163     @Mock UntrustedWifiNetworkFactory mUntrustedWifiNetworkFactory;
164     @Mock RestrictedWifiNetworkFactory mRestrictedWifiNetworkFactory;
165     @Mock WifiConfigManager mWifiConfigManager;
166     @Mock
167     WifiCarrierInfoStoreManagerData mWifiCarrierInfoStoreManagerData;
168     @Mock WifiNotificationManager mWifiNotificationManager;
169     @Mock Notification.Builder mNotificationBuilder;
170     @Mock Notification mNotification;
171     @Mock WifiDialogManager mWifiDialogManager;
172     @Mock WifiDialogManager.DialogHandle mDialogHandle;
173     @Mock
174     WifiCarrierInfoManager.OnImsiProtectedOrUserApprovedListener mListener;
175     @Mock WifiMetrics mWifiMetrics;
176     @Mock WifiCarrierInfoManager.OnCarrierOffloadDisabledListener mOnCarrierOffloadDisabledListener;
177     @Mock Clock mClock;
178     @Mock WifiNetworkSuggestionsManager mWifiNetworkSuggestionsManager;
179     @Mock DeviceConfigFacade mDeviceConfigFacade;
180     @Mock WifiStringResourceWrapper mWifiStringResourceWrapper;
181     @Mock WifiPseudonymManager mWifiPseudonymManager;
182 
183     private List<SubscriptionInfo> mSubInfoList;
184     private long mCurrentTimeMills = 1000L;
185 
186     MockitoSession mMockingSession = null;
187     TestLooper mLooper;
188     private WifiCarrierInfoStoreManagerData.DataSource mCarrierInfoDataSource;
189     private ImsiPrivacyProtectionExemptionStoreData.DataSource mImsiDataSource;
190     private ArgumentCaptor<BroadcastReceiver> mBroadcastReceiverCaptor =
191             ArgumentCaptor.forClass(BroadcastReceiver.class);
192     private ArgumentCaptor<SubscriptionManager.OnSubscriptionsChangedListener>
193             mListenerArgumentCaptor = ArgumentCaptor.forClass(
194                     SubscriptionManager.OnSubscriptionsChangedListener.class);
195 
196     private Consumer<Boolean>
197             mOobPseudonymFeatureFlagChangedListener;
198 
199     @Before
setUp()200     public void setUp() throws Exception {
201         MockitoAnnotations.initMocks(this);
202         mLooper = new TestLooper();
203         when(mContext.getSystemService(CarrierConfigManager.class))
204                 .thenReturn(mCarrierConfigManager);
205         when(mContext.getResources()).thenReturn(mResources);
206         when(mContext.getWifiOverlayApkPkgName()).thenReturn("test.com.android.wifi.resources");
207         when(mFrameworkFacade.makeNotificationBuilder(any(), anyString()))
208                 .thenReturn(mNotificationBuilder);
209         when(mFrameworkFacade.getBroadcast(any(), anyInt(), any(), anyInt()))
210                 .thenReturn(mock(PendingIntent.class));
211         when(mNotificationBuilder.setSmallIcon(any())).thenReturn(mNotificationBuilder);
212         when(mNotificationBuilder.setTicker(any())).thenReturn(mNotificationBuilder);
213         when(mNotificationBuilder.setContentTitle(any())).thenReturn(mNotificationBuilder);
214         when(mNotificationBuilder.setStyle(any())).thenReturn(mNotificationBuilder);
215         when(mNotificationBuilder.setContentIntent(any())).thenReturn(mNotificationBuilder);
216         when(mNotificationBuilder.setDeleteIntent(any())).thenReturn(mNotificationBuilder);
217         when(mNotificationBuilder.setShowWhen(anyBoolean())).thenReturn(mNotificationBuilder);
218         when(mNotificationBuilder.setLocalOnly(anyBoolean())).thenReturn(mNotificationBuilder);
219         when(mNotificationBuilder.setColor(anyInt())).thenReturn(mNotificationBuilder);
220         when(mNotificationBuilder.addAction(any())).thenReturn(mNotificationBuilder);
221         when(mNotificationBuilder.setTimeoutAfter(anyLong())).thenReturn(mNotificationBuilder);
222         when(mNotificationBuilder.build()).thenReturn(mNotification);
223         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
224                 .thenReturn(mDialogHandle);
225         when(mWifiInjector.makeWifiCarrierInfoStoreManagerData(any()))
226                 .thenReturn(mWifiCarrierInfoStoreManagerData);
227         when(mWifiInjector.getWifiConfigManager()).thenReturn(mWifiConfigManager);
228         when(mWifiInjector.getWifiNotificationManager()).thenReturn(mWifiNotificationManager);
229         when(mWifiInjector.getWifiDialogManager()).thenReturn(mWifiDialogManager);
230         when(mWifiInjector.getWifiNetworkSuggestionsManager())
231                 .thenReturn(mWifiNetworkSuggestionsManager);
232         when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
233         when(mWifiInjector.getWifiNetworkFactory()).thenReturn(mWifiNetworkFactory);
234         when(mWifiInjector.getUntrustedWifiNetworkFactory())
235                 .thenReturn(mUntrustedWifiNetworkFactory);
236         when(mWifiInjector.getRestrictedWifiNetworkFactory())
237                  .thenReturn(mRestrictedWifiNetworkFactory);
238         when(mContext.getStringResourceWrapper(anyInt(), anyInt()))
239                 .thenReturn(mWifiStringResourceWrapper);
240         mWifiCarrierInfoManager = new WifiCarrierInfoManager(mTelephonyManager,
241                 mSubscriptionManager, mWifiInjector, mFrameworkFacade, mContext, mWifiConfigStore,
242                 new Handler(mLooper.getLooper()), mWifiMetrics, mClock, mWifiPseudonymManager);
243         mWifiCarrierInfoManager.enableVerboseLogging(true);
244         ArgumentCaptor<WifiCarrierInfoStoreManagerData.DataSource>
245                 carrierInfoSourceArgumentCaptor =
246                 ArgumentCaptor.forClass(WifiCarrierInfoStoreManagerData.DataSource.class);
247         ArgumentCaptor<ImsiPrivacyProtectionExemptionStoreData.DataSource>
248                 imsiDataSourceArgumentCaptor =
249                 ArgumentCaptor.forClass(ImsiPrivacyProtectionExemptionStoreData.DataSource.class);
250         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), any(), any(), any());
251         verify(mWifiInjector).makeWifiCarrierInfoStoreManagerData(carrierInfoSourceArgumentCaptor
252                 .capture());
253         verify(mWifiInjector).makeImsiPrivacyProtectionExemptionStoreData(
254                 imsiDataSourceArgumentCaptor.capture());
255         ArgumentCaptor<Consumer> oobCaptor = ArgumentCaptor.forClass(Consumer.class);
256         verify(mDeviceConfigFacade).setOobPseudonymFeatureFlagChangedListener(oobCaptor.capture());
257         mOobPseudonymFeatureFlagChangedListener = oobCaptor.getValue();
258         mCarrierInfoDataSource = carrierInfoSourceArgumentCaptor.getValue();
259         mImsiDataSource = imsiDataSourceArgumentCaptor.getValue();
260         mImsiDataSource.fromDeserialized(new HashMap<>());
261         assertNotNull(mCarrierInfoDataSource);
262         mSubInfoList = new ArrayList<>();
263         mSubInfoList.add(mDataSubscriptionInfo);
264         mSubInfoList.add(mNonDataSubscriptionInfo);
265         when(mTelephonyManager.createForSubscriptionId(eq(DATA_SUBID)))
266                 .thenReturn(mDataTelephonyManager);
267         when(mTelephonyManager.createForSubscriptionId(eq(NON_DATA_SUBID)))
268                 .thenReturn(mNonDataTelephonyManager);
269         when(mTelephonyManager.getSimApplicationState(anyInt()))
270                 .thenReturn(TelephonyManager.SIM_STATE_LOADED);
271         when(mTelephonyManager.getActiveModemCount()).thenReturn(2);
272         when(mCarrierConfigManager.getConfigForSubId(anyInt()))
273                 .thenReturn(generateTestCarrierConfig(false));
274         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(mSubInfoList);
275         mMockingSession = ExtendedMockito.mockitoSession().strictness(Strictness.LENIENT)
276                 .mockStatic(SubscriptionManager.class).startMocking();
277 
278         doReturn(DATA_SUBID).when(
279                 () -> SubscriptionManager.getDefaultDataSubscriptionId());
280         doReturn(true).when(
281                 () -> SubscriptionManager.isValidSubscriptionId(DATA_SUBID));
282         doReturn(true).when(
283                 () -> SubscriptionManager.isValidSubscriptionId(NON_DATA_SUBID));
284 
285         when(mDataSubscriptionInfo.getCarrierId()).thenReturn(DATA_CARRIER_ID);
286         when(mDataSubscriptionInfo.getSubscriptionId()).thenReturn(DATA_SUBID);
287         when(mNonDataSubscriptionInfo.getCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
288         when(mNonDataSubscriptionInfo.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
289         when(mDataTelephonyManager.getSubscriberId()).thenReturn(DATA_FULL_IMSI);
290         when(mNonDataTelephonyManager.getSubscriberId()).thenReturn(NON_DATA_FULL_IMSI);
291         when(mDataTelephonyManager.getSimOperator()).thenReturn(DATA_OPERATOR_NUMERIC);
292         when(mDataTelephonyManager.getSimCarrierIdName()).thenReturn(CARRIER_NAME);
293         when(mNonDataTelephonyManager.getSimCarrierIdName()).thenReturn(null);
294         when(mNonDataTelephonyManager.getSimOperator())
295                 .thenReturn(NON_DATA_OPERATOR_NUMERIC);
296         when(mDataTelephonyManager.getSimApplicationState())
297                 .thenReturn(TelephonyManager.SIM_STATE_LOADED);
298         when(mNonDataTelephonyManager.getSimApplicationState())
299                 .thenReturn(TelephonyManager.SIM_STATE_LOADED);
300         when(mSubscriptionManager.getActiveSubscriptionIdList())
301                 .thenReturn(new int[]{DATA_SUBID, NON_DATA_SUBID});
302         when(mSubscriptionManager.getSubscriptionsInGroup(GROUP_UUID)).thenReturn(mSubInfoList);
303 
304         // setup resource strings for IMSI protection notification.
305         when(mResources.getString(eq(R.string.wifi_suggestion_imsi_privacy_title), anyString()))
306                 .thenAnswer(s -> "blah" + s.getArguments()[1]);
307         when(mResources.getString(eq(R.string.wifi_suggestion_imsi_privacy_content)))
308                 .thenReturn("blah");
309         when(mResources.getText(
310                 eq(R.string.wifi_suggestion_action_allow_imsi_privacy_exemption_carrier)))
311                 .thenReturn("blah");
312         when(mResources.getText(
313                 eq(R.string.wifi_suggestion_action_disallow_imsi_privacy_exemption_carrier)))
314                 .thenReturn("blah");
315         when(mResources.getString(
316                 eq(R.string.wifi_suggestion_imsi_privacy_exemption_confirmation_title)))
317                 .thenReturn("blah");
318         when(mResources.getString(
319                 eq(R.string.wifi_suggestion_imsi_privacy_exemption_confirmation_content),
320                 anyString())).thenAnswer(s -> "blah" + s.getArguments()[1]);
321         when(mResources.getText(
322                 eq(R.string.wifi_suggestion_action_allow_imsi_privacy_exemption_confirmation)))
323                 .thenReturn("blah");
324         when(mResources.getText(
325                 eq(R.string.wifi_suggestion_action_disallow_imsi_privacy_exemption_confirmation)))
326                 .thenReturn("blah");
327         when(mResources.getInteger(eq(R.integer.config_wifiImsiProtectionNotificationDelaySeconds)))
328                 .thenReturn(300);
329         mWifiCarrierInfoManager.addImsiProtectedOrUserApprovedListener(mListener);
330         verify(mSubscriptionManager).addOnSubscriptionsChangedListener(any(),
331                 mListenerArgumentCaptor.capture());
332         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
333         mLooper.dispatchAll();
334         when(mClock.getElapsedSinceBootMillis()).thenReturn(mCurrentTimeMills);
335     }
336 
337     @After
cleanUp()338     public void cleanUp() throws Exception {
339         if (mMockingSession != null) {
340             mMockingSession.finishMocking();
341         }
342     }
343 
344     /**
345      * Verify that the IMSI encryption info is not updated  when non
346      * {@link CarrierConfigManager#ACTION_CARRIER_CONFIG_CHANGED} intent is received.
347      *
348      * @throws Exception
349      */
350     @Test
receivedNonCarrierConfigChangedIntent()351     public void receivedNonCarrierConfigChangedIntent() throws Exception {
352         ArgumentCaptor<BroadcastReceiver> receiver =
353                 ArgumentCaptor.forClass(BroadcastReceiver.class);
354         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
355         receiver.getValue().onReceive(mContext, new Intent("placeholderIntent"));
356         verify(mCarrierConfigManager, never()).getConfig();
357     }
358 
generateTestCarrierConfig(boolean requiresImsiEncryption)359     private PersistableBundle generateTestCarrierConfig(boolean requiresImsiEncryption) {
360         PersistableBundle bundle = new PersistableBundle();
361         bundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
362         if (requiresImsiEncryption) {
363             bundle.putInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT,
364                     TelephonyManager.KEY_TYPE_WLAN);
365         }
366         return bundle;
367     }
368 
generateTestCarrierConfig(boolean requiresImsiEncryption, boolean requiresEapMethodPrefix)369     private PersistableBundle generateTestCarrierConfig(boolean requiresImsiEncryption,
370             boolean requiresEapMethodPrefix) {
371         PersistableBundle bundle = generateTestCarrierConfig(requiresImsiEncryption);
372         if (requiresEapMethodPrefix) {
373             bundle.putBoolean(CarrierConfigManager.ENABLE_EAP_METHOD_PREFIX_BOOL, true);
374         }
375         return bundle;
376     }
377 
378     /**
379      * Verify getting value about that if the IMSI encryption is required or not when
380      * {@link CarrierConfigManager#ACTION_CARRIER_CONFIG_CHANGED} intent is received.
381      */
382     @Test
receivedCarrierConfigChangedIntent()383     public void receivedCarrierConfigChangedIntent() throws Exception {
384         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
385                 .thenReturn(generateTestCarrierConfig(true));
386         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
387                 .thenReturn(generateTestCarrierConfig(false));
388         ArgumentCaptor<BroadcastReceiver> receiver =
389                 ArgumentCaptor.forClass(BroadcastReceiver.class);
390         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
391 
392         receiver.getValue().onReceive(mContext,
393                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
394 
395         assertTrue(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
396         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(NON_DATA_SUBID));
397     }
398 
399     @Test
receivedDefaultDataSubChangedIntent()400     public void receivedDefaultDataSubChangedIntent() throws Exception {
401         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
402                 .thenReturn(generateTestCarrierConfig(true));
403         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
404                 .thenReturn(generateTestCarrierConfig(false));
405         ArgumentCaptor<BroadcastReceiver> receiver =
406                 ArgumentCaptor.forClass(BroadcastReceiver.class);
407         when(mDeviceConfigFacade.isOobPseudonymEnabled()).thenReturn(true);
408         WifiStringResourceWrapper nonDataResourceWrapper = mock(WifiStringResourceWrapper.class);
409         when(mContext.getStringResourceWrapper(eq(NON_DATA_SUBID), eq(NON_DATA_CARRIER_ID)))
410                 .thenReturn(nonDataResourceWrapper);
411         when(nonDataResourceWrapper.getBoolean(
412                 eq(WifiCarrierInfoManager.CONFIG_WIFI_OOB_PSEUDONYM_ENABLED), anyBoolean()))
413                 .thenReturn(true);
414 
415         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
416         Intent intent = new Intent(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
417         intent.putExtra("subscription", NON_DATA_SUBID);
418         receiver.getValue().onReceive(mContext, intent);
419 
420         mLooper.dispatchAll();
421 
422         verify(mWifiPseudonymManager).retrieveOobPseudonymIfNeeded(NON_DATA_CARRIER_ID);
423         verify(mWifiPseudonymManager, never()).retrieveOobPseudonymIfNeeded(DATA_CARRIER_ID);
424     }
425 
426     /**
427      * Verify the auto-join may be restored if OOB pseudonym is enabled.
428      */
429     @Test
restoreAutoJoinForOobPseudonymEnabled()430     public void restoreAutoJoinForOobPseudonymEnabled() throws Exception {
431         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
432                 .thenReturn(generateTestCarrierConfig(true));
433         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
434                 .thenReturn(generateTestCarrierConfig(false));
435         when(mDeviceConfigFacade.isOobPseudonymEnabled()).thenReturn(true);
436         // enable OOB pseudonym for NON_DATA_SUBID
437         WifiStringResourceWrapper nonDataResourceWrapper = mock(WifiStringResourceWrapper.class);
438         when(mContext.getStringResourceWrapper(eq(NON_DATA_SUBID), eq(NON_DATA_CARRIER_ID)))
439                 .thenReturn(nonDataResourceWrapper);
440         when(nonDataResourceWrapper.getBoolean(
441                 eq(WifiCarrierInfoManager.CONFIG_WIFI_OOB_PSEUDONYM_ENABLED), anyBoolean()))
442                 .thenReturn(true);
443         mOobPseudonymFeatureFlagChangedListener.accept(/*isFeatureEnabled=*/ true);
444         mLooper.dispatchAll();
445 
446         verify(mListener).onImsiProtectedOrUserApprovalChanged(NON_DATA_CARRIER_ID, true);
447         verify(mListener, never())
448                 .onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
449         verify(mWifiConfigManager).saveToStore();
450         assertFalse(mWifiCarrierInfoManager.shouldFlipOnAutoJoinForOobPseudonym());
451 
452         ArgumentCaptor<BroadcastReceiver> receiver =
453                 ArgumentCaptor.forClass(BroadcastReceiver.class);
454         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
455 
456         receiver.getValue().onReceive(mContext,
457                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
458         mLooper.dispatchAll();
459 
460         assertFalse(mWifiCarrierInfoManager.shouldFlipOnAutoJoinForOobPseudonym());
461         // only called on Pseudonym feature enabled
462         verify(mListener, atMost(1))
463                 .onImsiProtectedOrUserApprovalChanged(NON_DATA_CARRIER_ID, true);
464         verify(mWifiPseudonymManager, times(2)).retrieveOobPseudonymIfNeeded(NON_DATA_CARRIER_ID);
465     }
466 
467     @Test
restoreAutoJoinForOobPseudonymDisabled()468     public void restoreAutoJoinForOobPseudonymDisabled() throws Exception {
469         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
470                 .thenReturn(generateTestCarrierConfig(true));
471         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
472                 .thenReturn(generateTestCarrierConfig(false));
473         when(mDeviceConfigFacade.isOobPseudonymEnabled()).thenReturn(false);
474         WifiStringResourceWrapper nonDataResourceWrapper = mock(WifiStringResourceWrapper.class);
475         when(mContext.getStringResourceWrapper(eq(NON_DATA_SUBID), eq(NON_DATA_CARRIER_ID)))
476                 .thenReturn(nonDataResourceWrapper);
477         when(nonDataResourceWrapper.getBoolean(
478                 eq(WifiCarrierInfoManager.CONFIG_WIFI_OOB_PSEUDONYM_ENABLED), anyBoolean()))
479                 .thenReturn(true);
480 
481         mOobPseudonymFeatureFlagChangedListener.accept(/*isFeatureEnabled=*/ false);
482         mLooper.dispatchAll();
483 
484         verify(mListener).onImsiProtectedOrUserApprovalChanged(NON_DATA_CARRIER_ID, false);
485         verify(mListener, never())
486                 .onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
487         verify(mWifiConfigManager).saveToStore();
488 
489         // do nothing for ACTION_CARRIER_CONFIG_CHANGED
490         ArgumentCaptor<BroadcastReceiver> receiver =
491                 ArgumentCaptor.forClass(BroadcastReceiver.class);
492         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
493 
494         receiver.getValue().onReceive(mContext,
495                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
496         mLooper.dispatchAll();
497         // only called on the previous event - feature disabled.
498         verify(mListener, atMost(1))
499                 .onImsiProtectedOrUserApprovalChanged(eq(NON_DATA_CARRIER_ID), anyBoolean());
500     }
501 
502     /**
503      * Validate when KEY_CARRIER_PROVISIONS_WIFI_MERGED_NETWORKS_BOOL is change from true to false,
504      * carrier offload will disable for merged network.
505      */
506     @Test
receivedCarrierConfigChangedAllowMergedNetworkToFalse()507     public void receivedCarrierConfigChangedAllowMergedNetworkToFalse() throws Exception {
508         assumeTrue(SdkLevel.isAtLeastS());
509         mWifiCarrierInfoManager.addOnCarrierOffloadDisabledListener(
510                 mOnCarrierOffloadDisabledListener);
511         PersistableBundle bundle = new PersistableBundle();
512         bundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
513         String key = CarrierConfigManager.KEY_CARRIER_PROVISIONS_WIFI_MERGED_NETWORKS_BOOL;
514         bundle.putBoolean(key, true);
515         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID)).thenReturn(bundle);
516         ArgumentCaptor<BroadcastReceiver> receiver =
517                 ArgumentCaptor.forClass(BroadcastReceiver.class);
518         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
519 
520         receiver.getValue().onReceive(mContext,
521                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
522         mLooper.dispatchAll();
523         assertTrue(mWifiCarrierInfoManager.areMergedCarrierWifiNetworksAllowed(DATA_SUBID));
524         verify(mOnCarrierOffloadDisabledListener, never()).onCarrierOffloadDisabled(anyInt(),
525                 anyBoolean());
526 
527         // When KEY_CARRIER_PROVISIONS_WIFI_MERGED_NETWORKS_BOOL change to false should send merged
528         // carrier offload disable callback.
529         PersistableBundle disallowedBundle = new PersistableBundle();
530         disallowedBundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
531         disallowedBundle.putBoolean(key, false);
532         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID)).thenReturn(disallowedBundle);
533         receiver.getValue().onReceive(mContext,
534                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
535         mLooper.dispatchAll();
536         assertFalse(mWifiCarrierInfoManager.areMergedCarrierWifiNetworksAllowed(DATA_SUBID));
537         verify(mOnCarrierOffloadDisabledListener).onCarrierOffloadDisabled(eq(DATA_SUBID),
538                 eq(true));
539     }
540 
541     /**
542      * Verify the IMSI encryption is cleared when the configuration in CarrierConfig is removed.
543      */
544     @Test
imsiEncryptionRequiredInfoIsCleared()545     public void imsiEncryptionRequiredInfoIsCleared() {
546         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
547                 .thenReturn(generateTestCarrierConfig(true));
548         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
549                 .thenReturn(generateTestCarrierConfig(true));
550         ArgumentCaptor<BroadcastReceiver> receiver =
551                 ArgumentCaptor.forClass(BroadcastReceiver.class);
552         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
553 
554         receiver.getValue().onReceive(mContext,
555                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
556         mLooper.dispatchAll();
557 
558         assertTrue(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
559         assertTrue(mWifiCarrierInfoManager.requiresImsiEncryption(NON_DATA_SUBID));
560 
561         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
562                 .thenReturn(generateTestCarrierConfig(false));
563         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
564                 .thenReturn(generateTestCarrierConfig(false));
565         receiver.getValue().onReceive(mContext,
566                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
567         mLooper.dispatchAll();
568 
569         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
570         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(NON_DATA_SUBID));
571     }
572 
573     /**
574      * Verify that if the IMSI encryption is downloaded and the OOB pseudonym
575      * retrieval is triggered.
576      */
577     @Test
availableOfImsiEncryptionInfoIsUpdatedAndOobPseudonymIsUpdated()578     public void availableOfImsiEncryptionInfoIsUpdatedAndOobPseudonymIsUpdated() {
579         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
580                 .thenReturn(generateTestCarrierConfig(true));
581         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
582                 .thenReturn(generateTestCarrierConfig(false));
583         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN))
584                 .thenReturn(null);
585         when(mNonDataTelephonyManager
586                 .getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN)).thenReturn(null);
587 
588         ArgumentCaptor<ContentObserver> observerCaptor =
589                 ArgumentCaptor.forClass(ContentObserver.class);
590         verify(mFrameworkFacade).registerContentObserver(eq(mContext), any(Uri.class), eq(false),
591                 observerCaptor.capture());
592         ContentObserver observer = observerCaptor.getValue();
593 
594         observer.onChange(false);
595         mLooper.dispatchAll();
596 
597         assertTrue(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
598         assertFalse(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(DATA_SUBID));
599 
600         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN))
601                 .thenReturn(mock(ImsiEncryptionInfo.class));
602         when(mDeviceConfigFacade.isOobPseudonymEnabled()).thenReturn(true);
603         WifiStringResourceWrapper nonDataResourceWrapper = mock(WifiStringResourceWrapper.class);
604         when(mContext.getStringResourceWrapper(eq(NON_DATA_SUBID), eq(NON_DATA_CARRIER_ID)))
605                 .thenReturn(nonDataResourceWrapper);
606         when(nonDataResourceWrapper.getBoolean(
607                 eq(WifiCarrierInfoManager.CONFIG_WIFI_OOB_PSEUDONYM_ENABLED), anyBoolean()))
608                 .thenReturn(true);
609 
610         observer.onChange(false);
611         mLooper.dispatchAll();
612 
613         assertTrue(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
614         assertTrue(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(DATA_SUBID));
615         verify(mWifiPseudonymManager).retrieveOobPseudonymIfNeeded(NON_DATA_CARRIER_ID);
616         verify(mWifiPseudonymManager, never()).retrieveOobPseudonymIfNeeded(DATA_CARRIER_ID);
617     }
618 
619     /**
620      * Verify that if the IMSI encryption information is cleared
621      */
622     @Test
availableOfImsiEncryptionInfoIsCleared()623     public void availableOfImsiEncryptionInfoIsCleared() {
624         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
625                 .thenReturn(generateTestCarrierConfig(true));
626         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
627                 .thenReturn(generateTestCarrierConfig(true));
628         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN))
629                 .thenReturn(mock(ImsiEncryptionInfo.class));
630         when(mNonDataTelephonyManager
631                 .getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN))
632                         .thenReturn(mock(ImsiEncryptionInfo.class));
633 
634         ArgumentCaptor<ContentObserver> observerCaptor =
635                 ArgumentCaptor.forClass(ContentObserver.class);
636         verify(mFrameworkFacade).registerContentObserver(eq(mContext), any(Uri.class), eq(false),
637                 observerCaptor.capture());
638         ContentObserver observer = observerCaptor.getValue();
639 
640         observer.onChange(false);
641         mLooper.dispatchAll();
642 
643         assertTrue(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(DATA_SUBID));
644         assertTrue(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(NON_DATA_SUBID));
645 
646         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN))
647                 .thenReturn(null);
648         when(mNonDataTelephonyManager
649                 .getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN)).thenReturn(null);
650 
651         observer.onChange(false);
652         mLooper.dispatchAll();
653 
654         assertFalse(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(DATA_SUBID));
655         assertFalse(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(NON_DATA_SUBID));
656     }
657 
658     @Test
getSimIdentityEapSim()659     public void getSimIdentityEapSim() {
660         final Pair<String, String> expectedIdentity = Pair.create(
661                 "13214561234567890@wlan.mnc456.mcc321.3gppnetwork.org", "");
662 
663         when(mDataTelephonyManager.getSubscriberId()).thenReturn("3214561234567890");
664         when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
665         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
666         WifiConfiguration simConfig =
667                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.SIM,
668                         WifiEnterpriseConfig.Phase2.NONE);
669         simConfig.carrierId = DATA_CARRIER_ID;
670 
671         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(simConfig));
672 
673         WifiConfiguration peapSimConfig =
674                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.PEAP,
675                         WifiEnterpriseConfig.Phase2.SIM);
676         peapSimConfig.carrierId = DATA_CARRIER_ID;
677 
678         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(peapSimConfig));
679         verify(mDataTelephonyManager, never()).getCarrierInfoForImsiEncryption(anyInt());
680     }
681 
682     @Test
getSimIdentityEapAka()683     public void getSimIdentityEapAka() {
684         final Pair<String, String> expectedIdentity = Pair.create(
685                 "03214561234567890@wlan.mnc456.mcc321.3gppnetwork.org", "");
686         when(mDataTelephonyManager.getSubscriberId()).thenReturn("3214561234567890");
687 
688         when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
689         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
690         WifiConfiguration akaConfig =
691                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.AKA,
692                         WifiEnterpriseConfig.Phase2.NONE);
693         akaConfig.carrierId = DATA_CARRIER_ID;
694 
695         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(akaConfig));
696 
697         WifiConfiguration peapAkaConfig =
698                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.PEAP,
699                         WifiEnterpriseConfig.Phase2.AKA);
700         peapAkaConfig.carrierId = DATA_CARRIER_ID;
701 
702         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(peapAkaConfig));
703         verify(mDataTelephonyManager, never()).getCarrierInfoForImsiEncryption(anyInt());
704     }
705 
706     @Test
getSimIdentityEapAkaPrime()707     public void getSimIdentityEapAkaPrime() {
708         final Pair<String, String> expectedIdentity = Pair.create(
709                 "63214561234567890@wlan.mnc456.mcc321.3gppnetwork.org", "");
710 
711         when(mDataTelephonyManager.getSubscriberId()).thenReturn("3214561234567890");
712         when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
713         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
714         WifiConfiguration akaPConfig =
715                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.AKA_PRIME,
716                         WifiEnterpriseConfig.Phase2.NONE);
717         akaPConfig.carrierId = DATA_CARRIER_ID;
718 
719         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(akaPConfig));
720 
721         WifiConfiguration peapAkaPConfig =
722                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.PEAP,
723                         WifiEnterpriseConfig.Phase2.AKA_PRIME);
724         peapAkaPConfig.carrierId = DATA_CARRIER_ID;
725 
726         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(peapAkaPConfig));
727         verify(mDataTelephonyManager, never()).getCarrierInfoForImsiEncryption(anyInt());
728     }
729 
730     /**
731      * Verify that an expected identity is returned when using the encrypted identity
732      * encoded by RFC4648.
733      */
734     @Test
getEncryptedIdentity_WithRfc4648()735     public void getEncryptedIdentity_WithRfc4648() throws Exception {
736         Cipher cipher = mock(Cipher.class);
737         PublicKey key = null;
738         String imsi = "3214561234567890";
739         String permanentIdentity = "03214561234567890@wlan.mnc456.mcc321.3gppnetwork.org";
740         String encryptedImsi = Base64.encodeToString(permanentIdentity.getBytes(), 0,
741                 permanentIdentity.getBytes().length, Base64.NO_WRAP);
742         String encryptedIdentity = "\0" + encryptedImsi;
743         final Pair<String, String> expectedIdentity = Pair.create(permanentIdentity,
744                 encryptedIdentity);
745         WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
746         doReturn(true).when(spyTu).requiresImsiEncryption(DATA_SUBID);
747 
748         // static mocking
749         MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
750                 Cipher.class).startMocking();
751         try {
752             lenient().when(Cipher.getInstance(anyString())).thenReturn(cipher);
753             when(cipher.doFinal(any(byte[].class))).thenReturn(permanentIdentity.getBytes());
754             when(mDataTelephonyManager.getSubscriberId()).thenReturn(imsi);
755             when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
756             ImsiEncryptionInfo info = mock(ImsiEncryptionInfo.class);
757             when(info.getPublicKey()).thenReturn(key);
758             when(info.getKeyIdentifier()).thenReturn(null);
759             when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(
760                     eq(TelephonyManager.KEY_TYPE_WLAN)))
761                     .thenReturn(info);
762             WifiConfiguration config =
763                     WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.AKA,
764                             WifiEnterpriseConfig.Phase2.NONE);
765             config.carrierId = DATA_CARRIER_ID;
766 
767             assertEquals(expectedIdentity, spyTu.getSimIdentity(config));
768         } finally {
769             session.finishMocking();
770         }
771     }
772 
773     /**
774      * Verify that an expected identity is returned when using the OOB Pseudonym.
775      */
776     @Test
getEncryptedIdentityWithOobPseudonymEnabled()777     public void getEncryptedIdentityWithOobPseudonymEnabled() throws Exception {
778         String expectedPseudonym = "abc123=1";
779         final Pair<String, String> expectedIdentity = Pair.create(expectedPseudonym,
780                 "");
781         WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
782         doReturn(true).when(spyTu).isOobPseudonymFeatureEnabled(DATA_CARRIER_ID);
783 
784         WifiConfiguration config =
785                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.AKA,
786                         WifiEnterpriseConfig.Phase2.NONE);
787         config.carrierId = DATA_CARRIER_ID;
788         PseudonymInfo pseudonymInfo = mock(PseudonymInfo.class);
789         when(pseudonymInfo.getPseudonym()).thenReturn(expectedPseudonym);
790         when(mWifiPseudonymManager.getValidPseudonymInfo(DATA_CARRIER_ID))
791                 .thenReturn(Optional.of(pseudonymInfo));
792 
793         assertEquals(expectedIdentity, spyTu.getSimIdentity(config));
794     }
795 
796     /**
797      * Verify that {@code null} will be returned when IMSI encryption failed.
798      *
799      * @throws Exception
800      */
801     @Test
getEncryptedIdentityFailed()802     public void getEncryptedIdentityFailed() throws Exception {
803         Cipher cipher = mock(Cipher.class);
804         String keyIdentifier = "key=testKey";
805         String imsi = "3214561234567890";
806         // static mocking
807         MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
808                 Cipher.class).startMocking();
809         try {
810             lenient().when(Cipher.getInstance(anyString())).thenReturn(cipher);
811             when(cipher.doFinal(any(byte[].class))).thenThrow(BadPaddingException.class);
812             when(mDataTelephonyManager.getSubscriberId()).thenReturn(imsi);
813             when(mDataTelephonyManager.getSimOperator()).thenReturn("321456");
814             ImsiEncryptionInfo info = mock(ImsiEncryptionInfo.class);
815             when(info.getPublicKey()).thenReturn(null);
816             when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(
817                     eq(TelephonyManager.KEY_TYPE_WLAN)))
818                     .thenReturn(info);
819             WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
820             doReturn(true).when(spyTu).requiresImsiEncryption(DATA_SUBID);
821 
822             WifiConfiguration config =
823                     WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.AKA,
824                             WifiEnterpriseConfig.Phase2.NONE);
825             config.carrierId = DATA_CARRIER_ID;
826 
827             assertNull(spyTu.getSimIdentity(config));
828         } finally {
829             session.finishMocking();
830         }
831     }
832 
833     @Test
getSimIdentity2DigitMnc()834     public void getSimIdentity2DigitMnc() {
835         final Pair<String, String> expectedIdentity = Pair.create(
836                 "1321560123456789@wlan.mnc056.mcc321.3gppnetwork.org", "");
837 
838         when(mDataTelephonyManager.getSubscriberId()).thenReturn("321560123456789");
839         when(mDataTelephonyManager.getSimOperator()).thenReturn("32156");
840         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
841         WifiConfiguration config =
842                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.SIM,
843                         WifiEnterpriseConfig.Phase2.NONE);
844         config.carrierId = DATA_CARRIER_ID;
845 
846         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(config));
847     }
848 
849     @Test
getSimIdentityUnknownMccMnc()850     public void getSimIdentityUnknownMccMnc() {
851         final Pair<String, String> expectedIdentity = Pair.create(
852                 "13214560123456789@wlan.mnc456.mcc321.3gppnetwork.org", "");
853 
854         when(mDataTelephonyManager.getSubscriberId()).thenReturn("3214560123456789");
855         when(mDataTelephonyManager.getSimOperator()).thenReturn(null);
856         when(mDataTelephonyManager.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(null);
857         WifiConfiguration config =
858                 WifiConfigurationTestUtil.createEapNetwork(WifiEnterpriseConfig.Eap.SIM,
859                         WifiEnterpriseConfig.Phase2.NONE);
860         config.carrierId = DATA_CARRIER_ID;
861 
862         assertEquals(expectedIdentity, mWifiCarrierInfoManager.getSimIdentity(config));
863     }
864 
865     @Test
getSimIdentityNonTelephonyConfig()866     public void getSimIdentityNonTelephonyConfig() {
867         when(mDataTelephonyManager.getSubscriberId()).thenReturn("321560123456789");
868         when(mDataTelephonyManager.getSimOperator()).thenReturn("32156");
869 
870         assertEquals(null,
871                 mWifiCarrierInfoManager.getSimIdentity(WifiConfigurationTestUtil.createEapNetwork(
872                         WifiEnterpriseConfig.Eap.TTLS, WifiEnterpriseConfig.Phase2.SIM)));
873         assertEquals(null,
874                 mWifiCarrierInfoManager.getSimIdentity(WifiConfigurationTestUtil.createEapNetwork(
875                         WifiEnterpriseConfig.Eap.PEAP, WifiEnterpriseConfig.Phase2.MSCHAPV2)));
876         assertEquals(null,
877                 mWifiCarrierInfoManager.getSimIdentity(WifiConfigurationTestUtil.createEapNetwork(
878                         WifiEnterpriseConfig.Eap.TLS, WifiEnterpriseConfig.Phase2.NONE)));
879         assertEquals(null,
880                 mWifiCarrierInfoManager.getSimIdentity(new WifiConfiguration()));
881     }
882 
883     /**
884      * Produce a base64 encoded length byte + data.
885      */
createSimChallengeRequest(byte[] challengeValue)886     private static String createSimChallengeRequest(byte[] challengeValue) {
887         byte[] challengeLengthAndValue = new byte[challengeValue.length + 1];
888         challengeLengthAndValue[0] = (byte) challengeValue.length;
889         for (int i = 0; i < challengeValue.length; ++i) {
890             challengeLengthAndValue[i + 1] = challengeValue[i];
891         }
892         return Base64.encodeToString(challengeLengthAndValue, android.util.Base64.NO_WRAP);
893     }
894 
895     /**
896      * Produce a base64 encoded data without length.
897      */
create2gUsimChallengeRequest(byte[] challengeValue)898     private static String create2gUsimChallengeRequest(byte[] challengeValue) {
899         return Base64.encodeToString(challengeValue, android.util.Base64.NO_WRAP);
900     }
901 
902     /**
903      * Produce a base64 encoded sres length byte + sres + kc length byte + kc.
904      */
createGsmSimAuthResponse(byte[] sresValue, byte[] kcValue)905     private static String createGsmSimAuthResponse(byte[] sresValue, byte[] kcValue) {
906         int overallLength = sresValue.length + kcValue.length + 2;
907         byte[] result = new byte[sresValue.length + kcValue.length + 2];
908         int idx = 0;
909         result[idx++] = (byte) sresValue.length;
910         for (int i = 0; i < sresValue.length; ++i) {
911             result[idx++] = sresValue[i];
912         }
913         result[idx++] = (byte) kcValue.length;
914         for (int i = 0; i < kcValue.length; ++i) {
915             result[idx++] = kcValue[i];
916         }
917         return Base64.encodeToString(result, Base64.NO_WRAP);
918     }
919 
920     /**
921      * Produce a base64 encoded sres + kc without length.
922      */
create2gUsimAuthResponse(byte[] sresValue, byte[] kcValue)923     private static String create2gUsimAuthResponse(byte[] sresValue, byte[] kcValue) {
924         int overallLength = sresValue.length + kcValue.length;
925         byte[] result = new byte[sresValue.length + kcValue.length];
926         int idx = 0;
927         for (int i = 0; i < sresValue.length; ++i) {
928             result[idx++] = sresValue[i];
929         }
930         for (int i = 0; i < kcValue.length; ++i) {
931             result[idx++] = kcValue[i];
932         }
933         return Base64.encodeToString(result, Base64.NO_WRAP);
934     }
935 
936     @Test
getGsmSimAuthResponseInvalidRequest()937     public void getGsmSimAuthResponseInvalidRequest() {
938         final String[] invalidRequests = { null, "", "XXXX" };
939         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
940                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
941 
942         assertEquals("", mWifiCarrierInfoManager.getGsmSimAuthResponse(invalidRequests, config));
943     }
944 
945     @Test
getGsmSimAuthResponseFailedSimResponse()946     public void getGsmSimAuthResponseFailedSimResponse() {
947         final String[] failedRequests = { "5E5F" };
948         when(mDataTelephonyManager.getIccAuthentication(anyInt(), anyInt(),
949                 eq(createSimChallengeRequest(new byte[] { 0x5e, 0x5f })))).thenReturn(null);
950         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
951                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
952 
953         assertEquals(null, mWifiCarrierInfoManager.getGsmSimAuthResponse(failedRequests, config));
954     }
955 
956     @Test
getGsmSimAuthResponseUsim()957     public void getGsmSimAuthResponseUsim() {
958         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
959                         TelephonyManager.AUTHTYPE_EAP_SIM,
960                         createSimChallengeRequest(new byte[] { 0x1b, 0x2b })))
961                 .thenReturn(createGsmSimAuthResponse(new byte[] { 0x1D, 0x2C },
962                                 new byte[] { 0x3B, 0x4A }));
963         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
964                         TelephonyManager.AUTHTYPE_EAP_SIM,
965                         createSimChallengeRequest(new byte[] { 0x01, 0x22 })))
966                 .thenReturn(createGsmSimAuthResponse(new byte[] { 0x11, 0x11 },
967                                 new byte[] { 0x12, 0x34 }));
968         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
969                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
970 
971         assertEquals(":3b4a:1d2c:1234:1111", mWifiCarrierInfoManager.getGsmSimAuthResponse(
972                         new String[] { "1B2B", "0122" }, config));
973     }
974 
975     @Test
getGsmSimpleSimAuthResponseInvalidRequest()976     public void getGsmSimpleSimAuthResponseInvalidRequest() {
977         final String[] invalidRequests = { null, "", "XXXX" };
978         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
979                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
980 
981         assertEquals("",
982                 mWifiCarrierInfoManager.getGsmSimpleSimAuthResponse(invalidRequests, config));
983     }
984 
985     @Test
getGsmSimpleSimAuthResponseFailedSimResponse()986     public void getGsmSimpleSimAuthResponseFailedSimResponse() {
987         final String[] failedRequests = { "5E5F" };
988         when(mDataTelephonyManager.getIccAuthentication(anyInt(), anyInt(),
989                 eq(createSimChallengeRequest(new byte[] { 0x5e, 0x5f })))).thenReturn(null);
990         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
991                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
992 
993         assertEquals(null,
994                 mWifiCarrierInfoManager.getGsmSimpleSimAuthResponse(failedRequests, config));
995     }
996 
997     @Test
getGsmSimpleSimAuthResponse()998     public void getGsmSimpleSimAuthResponse() {
999         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_SIM,
1000                         TelephonyManager.AUTHTYPE_EAP_SIM,
1001                         createSimChallengeRequest(new byte[] { 0x1a, 0x2b })))
1002                 .thenReturn(createGsmSimAuthResponse(new byte[] { 0x1D, 0x2C },
1003                                 new byte[] { 0x3B, 0x4A }));
1004         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_SIM,
1005                         TelephonyManager.AUTHTYPE_EAP_SIM,
1006                         createSimChallengeRequest(new byte[] { 0x01, 0x23 })))
1007                 .thenReturn(createGsmSimAuthResponse(new byte[] { 0x33, 0x22 },
1008                                 new byte[] { 0x11, 0x00 }));
1009         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1010                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
1011 
1012         assertEquals(":3b4a:1d2c:1100:3322", mWifiCarrierInfoManager.getGsmSimpleSimAuthResponse(
1013                         new String[] { "1A2B", "0123" }, config));
1014     }
1015 
1016     @Test
getGsmSimpleSimNoLengthAuthResponseInvalidRequest()1017     public void getGsmSimpleSimNoLengthAuthResponseInvalidRequest() {
1018         final String[] invalidRequests = { null, "", "XXXX" };
1019         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1020                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
1021 
1022         assertEquals("", mWifiCarrierInfoManager.getGsmSimpleSimNoLengthAuthResponse(
1023                 invalidRequests, config));
1024     }
1025 
1026     @Test
getGsmSimpleSimNoLengthAuthResponseFailedSimResponse()1027     public void getGsmSimpleSimNoLengthAuthResponseFailedSimResponse() {
1028         final String[] failedRequests = { "5E5F" };
1029         when(mDataTelephonyManager.getIccAuthentication(anyInt(), anyInt(),
1030                 eq(create2gUsimChallengeRequest(new byte[] { 0x5e, 0x5f })))).thenReturn(null);
1031         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1032                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
1033 
1034         assertEquals(null, mWifiCarrierInfoManager.getGsmSimpleSimNoLengthAuthResponse(
1035                 failedRequests, config));
1036     }
1037 
1038     @Test
getGsmSimpleSimNoLengthAuthResponse()1039     public void getGsmSimpleSimNoLengthAuthResponse() {
1040         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_SIM,
1041                         TelephonyManager.AUTHTYPE_EAP_SIM,
1042                         create2gUsimChallengeRequest(new byte[] { 0x1a, 0x2b })))
1043                 .thenReturn(create2gUsimAuthResponse(new byte[] { 0x1a, 0x2b, 0x3c, 0x4d },
1044                                 new byte[] { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f, 0x7a, 0x1a }));
1045         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_SIM,
1046                         TelephonyManager.AUTHTYPE_EAP_SIM,
1047                         create2gUsimChallengeRequest(new byte[] { 0x01, 0x23 })))
1048                 .thenReturn(create2gUsimAuthResponse(new byte[] { 0x12, 0x34, 0x56, 0x78 },
1049                                 new byte[] { 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78 }));
1050         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1051                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
1052 
1053         assertEquals(":1a2b3c4d5e6f7a1a:1a2b3c4d:1234567812345678:12345678",
1054                 mWifiCarrierInfoManager.getGsmSimpleSimNoLengthAuthResponse(
1055                         new String[] { "1A2B", "0123" }, config));
1056     }
1057 
1058     /**
1059      * Produce a base64 encoded tag + res length byte + res + ck length byte + ck + ik length byte +
1060      * ik.
1061      */
create3GSimAuthUmtsAuthResponse(byte[] res, byte[] ck, byte[] ik)1062     private static String create3GSimAuthUmtsAuthResponse(byte[] res, byte[] ck, byte[] ik) {
1063         byte[] result = new byte[res.length + ck.length + ik.length + 4];
1064         int idx = 0;
1065         result[idx++] = (byte) 0xdb;
1066         result[idx++] = (byte) res.length;
1067         for (int i = 0; i < res.length; ++i) {
1068             result[idx++] = res[i];
1069         }
1070         result[idx++] = (byte) ck.length;
1071         for (int i = 0; i < ck.length; ++i) {
1072             result[idx++] = ck[i];
1073         }
1074         result[idx++] = (byte) ik.length;
1075         for (int i = 0; i < ik.length; ++i) {
1076             result[idx++] = ik[i];
1077         }
1078         return Base64.encodeToString(result, Base64.NO_WRAP);
1079     }
1080 
create3GSimAuthUmtsAutsResponse(byte[] auts)1081     private static String create3GSimAuthUmtsAutsResponse(byte[] auts) {
1082         byte[] result = new byte[auts.length + 2];
1083         int idx = 0;
1084         result[idx++] = (byte) 0xdc;
1085         result[idx++] = (byte) auts.length;
1086         for (int i = 0; i < auts.length; ++i) {
1087             result[idx++] = auts[i];
1088         }
1089         return Base64.encodeToString(result, Base64.NO_WRAP);
1090     }
1091 
1092     @Test
get3GAuthResponseInvalidRequest()1093     public void get3GAuthResponseInvalidRequest() {
1094         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1095                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1096 
1097         assertEquals(null, mWifiCarrierInfoManager.get3GAuthResponse(
1098                 new SimAuthRequestData(0, 0, "SSID", new String[]{"0123"}), config));
1099         assertEquals(null, mWifiCarrierInfoManager.get3GAuthResponse(
1100                 new SimAuthRequestData(0, 0, "SSID", new String[]{"xyz2", "1234"}),
1101                 config));
1102         verifyNoMoreInteractions(mDataTelephonyManager);
1103     }
1104 
1105     @Test
get3GAuthResponseNullIccAuthentication()1106     public void get3GAuthResponseNullIccAuthentication() {
1107         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
1108                         TelephonyManager.AUTHTYPE_EAP_AKA, "AgEjAkVn")).thenReturn(null);
1109         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1110                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1111         SimAuthResponseData response = mWifiCarrierInfoManager.get3GAuthResponse(
1112                 new SimAuthRequestData(0, 0, "SSID", new String[]{"0123", "4567"}),
1113                 config);
1114 
1115         assertNull(response);
1116     }
1117 
1118     @Test
get3GAuthResponseIccAuthenticationTooShort()1119     public void get3GAuthResponseIccAuthenticationTooShort() {
1120         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
1121                         TelephonyManager.AUTHTYPE_EAP_AKA, "AgEjAkVn"))
1122                 .thenReturn(Base64.encodeToString(new byte[] {(byte) 0xdc}, Base64.NO_WRAP));
1123         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1124                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1125         SimAuthResponseData response = mWifiCarrierInfoManager.get3GAuthResponse(
1126                 new SimAuthRequestData(0, 0, "SSID", new String[]{"0123", "4567"}),
1127                 config);
1128 
1129         assertNull(response);
1130     }
1131 
1132     @Test
get3GAuthResponseBadTag()1133     public void get3GAuthResponseBadTag() {
1134         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
1135                         TelephonyManager.AUTHTYPE_EAP_AKA, "AgEjAkVn"))
1136                 .thenReturn(Base64.encodeToString(new byte[] {0x31, 0x1, 0x2, 0x3, 0x4},
1137                                 Base64.NO_WRAP));
1138         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1139                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1140         SimAuthResponseData response = mWifiCarrierInfoManager.get3GAuthResponse(
1141                 new SimAuthRequestData(0, 0, "SSID", new String[]{"0123", "4567"}),
1142                 config);
1143 
1144         assertNull(response);
1145     }
1146 
1147     @Test
get3GAuthResponseUmtsAuth()1148     public void get3GAuthResponseUmtsAuth() {
1149         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
1150                         TelephonyManager.AUTHTYPE_EAP_AKA, "AgEjAkVn"))
1151                 .thenReturn(create3GSimAuthUmtsAuthResponse(new byte[] {0x11, 0x12},
1152                                 new byte[] {0x21, 0x22, 0x23}, new byte[] {0x31}));
1153         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1154                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1155         SimAuthResponseData response = mWifiCarrierInfoManager.get3GAuthResponse(
1156                 new SimAuthRequestData(0, 0, "SSID", new String[]{"0123", "4567"}),
1157                 config);
1158 
1159         assertNotNull(response);
1160         assertEquals("UMTS-AUTH", response.type);
1161         assertEquals(":31:212223:1112", response.response);
1162     }
1163 
1164     @Test
get3GAuthResponseUmtsAuts()1165     public void get3GAuthResponseUmtsAuts() {
1166         when(mDataTelephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_USIM,
1167                         TelephonyManager.AUTHTYPE_EAP_AKA, "AgEjAkVn"))
1168                 .thenReturn(create3GSimAuthUmtsAutsResponse(new byte[] {0x22, 0x33}));
1169         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1170                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1171         SimAuthResponseData response = mWifiCarrierInfoManager.get3GAuthResponse(
1172                 new SimAuthRequestData(0, 0, "SSID", new String[]{"0123", "4567"}),
1173                 config);
1174         assertNotNull(response);
1175         assertEquals("UMTS-AUTS", response.type);
1176         assertEquals(":2233", response.response);
1177     }
1178 
1179     /**
1180      * Verify that anonymous identity should be a valid format based on MCC/MNC of current SIM.
1181      */
1182     @Test
getAnonymousIdentityWithSim()1183     public void getAnonymousIdentityWithSim() {
1184         String mccmnc = "123456";
1185         String expectedIdentity = ANONYMOUS_IDENTITY;
1186         when(mDataTelephonyManager.getSimOperator()).thenReturn(mccmnc);
1187         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1188                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1189 
1190         assertEquals(expectedIdentity,
1191                 mWifiCarrierInfoManager.getAnonymousIdentityWith3GppRealm(config));
1192     }
1193 
1194     /**
1195      * Verify that anonymous identity should be {@code null} when SIM is absent.
1196      */
1197     @Test
getAnonymousIdentityWithoutSim()1198     public void getAnonymousIdentityWithoutSim() {
1199         when(mDataTelephonyManager.getSimApplicationState())
1200                 .thenReturn(TelephonyManager.SIM_STATE_NOT_READY);
1201         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1202                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1203 
1204         assertNull(mWifiCarrierInfoManager.getAnonymousIdentityWith3GppRealm(config));
1205     }
1206 
1207     /**
1208      * Verify SIM is present.
1209      */
1210     @Test
isSimPresentWithValidSubscriptionIdList()1211     public void isSimPresentWithValidSubscriptionIdList() {
1212         SubscriptionInfo subInfo1 = mock(SubscriptionInfo.class);
1213         when(subInfo1.getSubscriptionId()).thenReturn(DATA_SUBID);
1214         SubscriptionInfo subInfo2 = mock(SubscriptionInfo.class);
1215         when(subInfo2.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
1216         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1217                 .thenReturn(Arrays.asList(subInfo1, subInfo2));
1218         assertTrue(mWifiCarrierInfoManager.isSimReady(DATA_SUBID));
1219     }
1220 
1221     /**
1222      * Verify SIM is not present.
1223      */
1224     @Test
isSimPresentWithInvalidOrEmptySubscriptionIdList()1225     public void isSimPresentWithInvalidOrEmptySubscriptionIdList() {
1226         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1227                 .thenReturn(Collections.emptyList());
1228         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
1229         mLooper.dispatchAll();
1230 
1231         assertFalse(mWifiCarrierInfoManager.isSimReady(DATA_SUBID));
1232 
1233         SubscriptionInfo subInfo = mock(SubscriptionInfo.class);
1234         when(subInfo.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
1235         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1236                 .thenReturn(Arrays.asList(subInfo));
1237         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
1238         mLooper.dispatchAll();
1239         assertFalse(mWifiCarrierInfoManager.isSimReady(DATA_SUBID));
1240     }
1241 
1242     /**
1243      * Verify SIM is considered not present when SIM state is not ready
1244      */
1245     @Test
isSimPresentWithValidSubscriptionIdListWithSimStateNotReady()1246     public void isSimPresentWithValidSubscriptionIdListWithSimStateNotReady() {
1247         SubscriptionInfo subInfo1 = mock(SubscriptionInfo.class);
1248         when(subInfo1.getSubscriptionId()).thenReturn(DATA_SUBID);
1249         SubscriptionInfo subInfo2 = mock(SubscriptionInfo.class);
1250         when(subInfo2.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
1251         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1252                 .thenReturn(Arrays.asList(subInfo1, subInfo2));
1253         when(mDataTelephonyManager.getSimApplicationState())
1254                 .thenReturn(TelephonyManager.SIM_STATE_NETWORK_LOCKED);
1255         assertFalse(mWifiCarrierInfoManager.isSimReady(DATA_SUBID));
1256     }
1257 
1258     /**
1259      * Verify SIM is considered not present when carrierConfig is not ready.
1260      */
1261     @Test
isSimPresentWithValidSubscriptionIdListWithCarrierConfigNotReady()1262     public void isSimPresentWithValidSubscriptionIdListWithCarrierConfigNotReady() {
1263         SubscriptionInfo subInfo1 = mock(SubscriptionInfo.class);
1264         when(subInfo1.getSubscriptionId()).thenReturn(DATA_SUBID);
1265         SubscriptionInfo subInfo2 = mock(SubscriptionInfo.class);
1266         when(subInfo2.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
1267         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1268                 .thenReturn(Arrays.asList(subInfo1, subInfo2));
1269         when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(null);
1270         ArgumentCaptor<BroadcastReceiver> receiver =
1271                 ArgumentCaptor.forClass(BroadcastReceiver.class);
1272         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
1273         receiver.getValue().onReceive(mContext,
1274                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
1275 
1276         assertFalse(mWifiCarrierInfoManager.isSimReady(DATA_SUBID));
1277     }
1278 
1279     /**
1280      * The active SubscriptionInfo List may be null or empty from Telephony.
1281      */
1282     @Test
getBestMatchSubscriptionIdWithEmptyActiveSubscriptionInfoList()1283     public void getBestMatchSubscriptionIdWithEmptyActiveSubscriptionInfoList() {
1284         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1285                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1286         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
1287         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
1288         mLooper.dispatchAll();
1289 
1290         assertEquals(INVALID_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1291 
1292         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1293                 .thenReturn(Collections.emptyList());
1294         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
1295         mLooper.dispatchAll();
1296 
1297         assertEquals(INVALID_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1298     }
1299 
1300     /**
1301      * The matched Subscription ID should be that of data SIM when carrier ID is not specified.
1302      */
1303     @Test
getBestMatchSubscriptionIdForEnterpriseWithoutCarrierIdFieldForSimConfig()1304     public void getBestMatchSubscriptionIdForEnterpriseWithoutCarrierIdFieldForSimConfig() {
1305         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1306                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1307 
1308         assertEquals(DATA_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1309     }
1310 
1311     /**
1312      * The matched Subscription ID should be invalid if the configuration does not require
1313      * SIM card and the carrier ID is not specified.
1314      */
1315     @Test
getBestMatchSubscriptionIdForEnterpriseWithoutCarrierIdFieldForNonSimConfig()1316     public void getBestMatchSubscriptionIdForEnterpriseWithoutCarrierIdFieldForNonSimConfig() {
1317         WifiConfiguration config = new WifiConfiguration();
1318 
1319         assertEquals(INVALID_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1320     }
1321 
1322     /**
1323      * If the carrier ID is specifed for EAP-SIM configuration, the corresponding Subscription ID
1324      * should be returned.
1325      */
1326     @Test
getBestMatchSubscriptionIdForEnterpriseWithNonDataCarrierId()1327     public void getBestMatchSubscriptionIdForEnterpriseWithNonDataCarrierId() {
1328         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1329                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1330         config.carrierId = NON_DATA_CARRIER_ID;
1331 
1332         assertEquals(NON_DATA_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1333 
1334         config.carrierId = DATA_CARRIER_ID;
1335         assertEquals(DATA_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1336     }
1337 
1338     /**
1339      * If the passpoint profile have valid carrier ID, the matching sub ID should be returned.
1340      */
1341     @Test
getBestMatchSubscriptionIdForPasspointWithValidCarrierId()1342     public void getBestMatchSubscriptionIdForPasspointWithValidCarrierId() {
1343         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1344                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1345         config.carrierId = DATA_CARRIER_ID;
1346         WifiConfiguration spyConfig = spy(config);
1347         doReturn(true).when(spyConfig).isPasspoint();
1348 
1349         assertEquals(DATA_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(spyConfig));
1350     }
1351 
1352     /**
1353      * If there is no matching SIM card, the matching sub ID should be invalid.
1354      */
1355     @Test
getBestMatchSubscriptionIdForPasspointInvalidCarrierId()1356     public void getBestMatchSubscriptionIdForPasspointInvalidCarrierId() {
1357         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1358                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1359         WifiConfiguration spyConfig = spy(config);
1360         doReturn(true).when(spyConfig).isPasspoint();
1361 
1362         assertEquals(INVALID_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(spyConfig));
1363     }
1364 
1365     /**
1366      * The matched Subscription ID should be invalid if the SIM card for the specified carrier ID
1367      * is absent.
1368      */
1369     @Test
getBestMatchSubscriptionIdWithDeactiveCarrierId()1370     public void getBestMatchSubscriptionIdWithDeactiveCarrierId() {
1371         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1372                 WifiEnterpriseConfig.Eap.AKA, WifiEnterpriseConfig.Phase2.NONE);
1373         config.carrierId = DEACTIVE_CARRIER_ID;
1374 
1375         assertEquals(INVALID_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(config));
1376     }
1377 
1378     /**
1379      * The matched Subscription ID should be invalid if the config is null;
1380      */
1381     @Test
getBestMatchSubscriptionIdWithNullConfig()1382     public void getBestMatchSubscriptionIdWithNullConfig() {
1383         assertEquals(INVALID_SUBID, mWifiCarrierInfoManager.getBestMatchSubscriptionId(null));
1384     }
1385 
1386     /**
1387      * Verify that the result is null if no active SIM is matched.
1388      */
1389     @Test
getMatchingImsiCarrierIdWithDeactiveCarrierId()1390     public void getMatchingImsiCarrierIdWithDeactiveCarrierId() {
1391         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1392                 .thenReturn(Collections.emptyList());
1393 
1394         assertNull(mWifiCarrierInfoManager.getMatchingImsiBySubId(INVALID_SUBID));
1395     }
1396 
1397     /**
1398      * Verify that a SIM is matched with carrier ID, and it requires IMSI encryption,
1399      * when the IMSI encryption info is not available, it should return null.
1400      */
1401     @Test
getMatchingImsiCarrierIdWithValidCarrierIdForImsiEncryptionCheck()1402     public void getMatchingImsiCarrierIdWithValidCarrierIdForImsiEncryptionCheck() {
1403         WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
1404         doReturn(true).when(spyTu).requiresImsiEncryption(DATA_SUBID);
1405         doReturn(false).when(spyTu).isImsiEncryptionInfoAvailable(DATA_SUBID);
1406 
1407         assertNull(spyTu.getMatchingImsiBySubId(DATA_SUBID));
1408     }
1409 
1410     /**
1411      * Verify that a SIM is matched with carrier ID, and OOB pseudonym is enabled,
1412      * when the OOB pseudonym is not available, it should return null.
1413      */
1414     @Test
getMatchingImsiCarrierIdWithValidCarrierIdForOobPseudonymCheck()1415     public void getMatchingImsiCarrierIdWithValidCarrierIdForOobPseudonymCheck() {
1416         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1417         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1418         WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
1419         doReturn(true).when(spyTu).isOobPseudonymFeatureEnabled(DATA_CARRIER_ID);
1420         when(mWifiPseudonymManager.getValidPseudonymInfo(DATA_CARRIER_ID))
1421                 .thenReturn(Optional.empty());
1422 
1423         assertNull(spyTu.getMatchingImsiBySubId(DATA_SUBID));
1424 
1425         verify(mWifiPseudonymManager).retrievePseudonymOnFailureTimeoutExpired(DATA_CARRIER_ID);
1426     }
1427 
1428     /**
1429      * Verify that if there is SIM card whose carrier ID is the same as the input, the correct IMSI
1430      * and carrier ID would be returned.
1431      */
1432     @Test
getMatchingImsiCarrierIdWithValidCarrierId()1433     public void getMatchingImsiCarrierIdWithValidCarrierId() {
1434         assertEquals(DATA_FULL_IMSI,
1435                 mWifiCarrierInfoManager.getMatchingImsiBySubId(DATA_SUBID));
1436     }
1437 
1438     /**
1439      * Verify that if there is no SIM, it should match nothing.
1440      */
1441     @Test
getMatchingImsiCarrierIdWithEmptyActiveSubscriptionInfoList()1442     public void getMatchingImsiCarrierIdWithEmptyActiveSubscriptionInfoList() {
1443         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
1444         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
1445         mLooper.dispatchAll();
1446 
1447         assertNull(mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1448 
1449         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1450                 .thenReturn(Collections.emptyList());
1451         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
1452         mLooper.dispatchAll();
1453 
1454         assertNull(mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1455     }
1456 
1457     /**
1458      * Verify that if there is no matching SIM, it should match nothing.
1459      */
1460     @Test
getMatchingImsiCarrierIdWithNoMatchImsi()1461     public void getMatchingImsiCarrierIdWithNoMatchImsi() {
1462         // data SIM is MNO.
1463         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1464         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1465         // non data SIM is MNO.
1466         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1467         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1468 
1469         assertNull(mWifiCarrierInfoManager.getMatchingImsiCarrierId(NO_MATCH_PREFIX_IMSI));
1470     }
1471 
1472     /**
1473      * Verify that if the matched SIM is the default data SIM and a MNO SIM, the information of it
1474      * should be returned.
1475      */
1476     @Test
getMatchingImsiCarrierIdForDataAndMnoSimMatch()1477     public void getMatchingImsiCarrierIdForDataAndMnoSimMatch() {
1478         // data SIM is MNO.
1479         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1480         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1481         // non data SIM is MNO.
1482         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1483         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1484 
1485         Pair<String, Integer> ic = mWifiCarrierInfoManager
1486                 .getMatchingImsiCarrierId(MATCH_PREFIX_IMSI);
1487 
1488         assertEquals(new Pair<>(DATA_FULL_IMSI, DATA_CARRIER_ID), ic);
1489 
1490         // non data SIM is MVNO
1491         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc())
1492                 .thenReturn(PARENT_NON_DATA_CARRIER_ID);
1493         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1494 
1495         assertEquals(new Pair<>(DATA_FULL_IMSI, DATA_CARRIER_ID),
1496                 mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1497 
1498         // non data SIM doesn't match.
1499         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1500         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1501         when(mNonDataTelephonyManager.getSubscriberId()).thenReturn(NO_MATCH_FULL_IMSI);
1502         when(mNonDataTelephonyManager.getSimOperator())
1503                 .thenReturn(NO_MATCH_OPERATOR_NUMERIC);
1504 
1505         assertEquals(new Pair<>(DATA_FULL_IMSI, DATA_CARRIER_ID),
1506                 mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1507     }
1508 
1509     /**
1510      * Verify that if the matched SIM is the default data SIM and a MVNO SIM, and no MNO SIM was
1511      * matched, the information of it should be returned.
1512      */
1513     @Test
getMatchingImsiCarrierIdForDataAndMvnoSimMatch()1514     public void getMatchingImsiCarrierIdForDataAndMvnoSimMatch() {
1515         // data SIM is MVNO.
1516         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(PARENT_DATA_CARRIER_ID);
1517         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1518         // non data SIM is MVNO.
1519         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc())
1520                 .thenReturn(PARENT_NON_DATA_CARRIER_ID);
1521         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1522 
1523         Pair<String, Integer> ic = mWifiCarrierInfoManager
1524                 .getMatchingImsiCarrierId(MATCH_PREFIX_IMSI);
1525 
1526         assertEquals(new Pair<>(DATA_FULL_IMSI, DATA_CARRIER_ID), ic);
1527 
1528         // non data SIM doesn't match.
1529         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1530         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1531         when(mNonDataTelephonyManager.getSubscriberId()).thenReturn(NO_MATCH_FULL_IMSI);
1532         when(mNonDataTelephonyManager.getSimOperator())
1533                 .thenReturn(NO_MATCH_OPERATOR_NUMERIC);
1534 
1535         assertEquals(new Pair<>(DATA_FULL_IMSI, DATA_CARRIER_ID),
1536                 mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1537     }
1538 
1539     /**
1540      * Verify that if the matched SIM is a MNO SIM, even the default data SIM is matched as a MVNO
1541      * SIM, the information of MNO SIM still should be returned.
1542      */
1543     @Test
getMatchingImsiCarrierIdForNonDataAndMnoSimMatch()1544     public void getMatchingImsiCarrierIdForNonDataAndMnoSimMatch() {
1545         // data SIM is MVNO.
1546         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(PARENT_DATA_CARRIER_ID);
1547         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1548         // non data SIM is MNO.
1549         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1550         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1551 
1552 
1553         Pair<String, Integer> ic = mWifiCarrierInfoManager
1554                 .getMatchingImsiCarrierId(MATCH_PREFIX_IMSI);
1555 
1556         assertEquals(new Pair<>(NON_DATA_FULL_IMSI, NON_DATA_CARRIER_ID), ic);
1557 
1558         // data SIM doesn't match
1559         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1560         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1561         when(mDataTelephonyManager.getSubscriberId()).thenReturn(NO_MATCH_FULL_IMSI);
1562         when(mDataTelephonyManager.getSimOperator()).thenReturn(NO_MATCH_OPERATOR_NUMERIC);
1563 
1564         assertEquals(new Pair<>(NON_DATA_FULL_IMSI, NON_DATA_CARRIER_ID),
1565                 mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1566     }
1567 
1568     /**
1569      * Verify that if only a MVNO SIM is matched, the information of it should be returned.
1570      */
1571     @Test
getMatchingImsiCarrierIdForMvnoSimMatch()1572     public void getMatchingImsiCarrierIdForMvnoSimMatch() {
1573         // data SIM is MNO, but IMSI doesn't match.
1574         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1575         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1576         when(mDataTelephonyManager.getSubscriberId()).thenReturn(NO_MATCH_FULL_IMSI);
1577         when(mDataTelephonyManager.getSimOperator()).thenReturn(NO_MATCH_OPERATOR_NUMERIC);
1578         // non data SIM is MVNO.
1579         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc())
1580                 .thenReturn(PARENT_NON_DATA_CARRIER_ID);
1581         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1582 
1583         assertEquals(new Pair<>(NON_DATA_FULL_IMSI, NON_DATA_CARRIER_ID),
1584                 mWifiCarrierInfoManager.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1585     }
1586 
1587     /**
1588      * Verify that a SIM is matched, and it requires IMSI encryption, when the IMSI encryption
1589      * info is not available, it should return null.
1590      */
1591     @Test
getMatchingImsiCarrierIdForImsiEncryptionCheck()1592     public void getMatchingImsiCarrierIdForImsiEncryptionCheck() {
1593         // data SIM is MNO.
1594         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1595         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1596         // non data SIM does not match.
1597         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1598         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1599         when(mNonDataTelephonyManager.getSubscriberId()).thenReturn(NO_MATCH_FULL_IMSI);
1600         when(mNonDataTelephonyManager.getSimOperator())
1601                 .thenReturn(NO_MATCH_OPERATOR_NUMERIC);
1602         WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
1603         doReturn(true).when(spyTu).requiresImsiEncryption(eq(DATA_SUBID));
1604         doReturn(false).when(spyTu).isImsiEncryptionInfoAvailable(eq(DATA_SUBID));
1605 
1606         assertNull(spyTu.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1607     }
1608 
1609     /**
1610      * Verify that a SIM is matched, and the OOB pseudonym is enabled, when the pseudonym info
1611      * is not available, it should return null.
1612      */
1613     @Test
getMatchingImsiCarrierIdForOobPseudonymCheck()1614     public void getMatchingImsiCarrierIdForOobPseudonymCheck() {
1615         // data SIM is MNO.
1616         when(mDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(DATA_CARRIER_ID);
1617         when(mDataTelephonyManager.getSimCarrierId()).thenReturn(DATA_CARRIER_ID);
1618         // non data SIM does not match.
1619         when(mNonDataTelephonyManager.getCarrierIdFromSimMccMnc()).thenReturn(NON_DATA_CARRIER_ID);
1620         when(mNonDataTelephonyManager.getSimCarrierId()).thenReturn(NON_DATA_CARRIER_ID);
1621         when(mNonDataTelephonyManager.getSubscriberId()).thenReturn(NO_MATCH_FULL_IMSI);
1622         when(mNonDataTelephonyManager.getSimOperator())
1623                 .thenReturn(NO_MATCH_OPERATOR_NUMERIC);
1624         WifiCarrierInfoManager spyTu = spy(mWifiCarrierInfoManager);
1625         doReturn(true).when(spyTu).isOobPseudonymFeatureEnabled(DATA_CARRIER_ID);
1626         when(mWifiPseudonymManager.getValidPseudonymInfo(DATA_CARRIER_ID))
1627                 .thenReturn(Optional.empty());
1628 
1629         assertNull(spyTu.getMatchingImsiCarrierId(MATCH_PREFIX_IMSI));
1630 
1631         verify(mWifiPseudonymManager).retrievePseudonymOnFailureTimeoutExpired(DATA_CARRIER_ID);
1632     }
1633 
1634     /**
1635      * Verify that if there is no any SIM card, the carrier ID should be updated.
1636      */
1637     @Test
tryUpdateCarrierIdForPasspointWithEmptyActiveSubscriptionList()1638     public void tryUpdateCarrierIdForPasspointWithEmptyActiveSubscriptionList() {
1639         PasspointConfiguration config = mock(PasspointConfiguration.class);
1640         when(config.getCarrierId()).thenReturn(DATA_CARRIER_ID);
1641         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
1642 
1643         assertFalse(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(config));
1644 
1645         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1646                 .thenReturn(Collections.emptyList());
1647 
1648         assertFalse(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(config));
1649     }
1650 
1651     /**
1652      * Verify that if the carrier ID has been assigned, it shouldn't be updated.
1653      */
1654     @Test
tryUpdateCarrierIdForPasspointWithValidCarrieId()1655     public void tryUpdateCarrierIdForPasspointWithValidCarrieId() {
1656         PasspointConfiguration config = mock(PasspointConfiguration.class);
1657         when(config.getCarrierId()).thenReturn(DATA_CARRIER_ID);
1658 
1659         assertFalse(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(config));
1660     }
1661 
1662     /**
1663      * Verify that if the passpoint profile doesn't have SIM credential, it shouldn't be updated.
1664      */
1665     @Test
tryUpdateCarrierIdForPasspointWithNonSimCredential()1666     public void tryUpdateCarrierIdForPasspointWithNonSimCredential() {
1667         Credential credential = mock(Credential.class);
1668         PasspointConfiguration spyConfig = spy(new PasspointConfiguration());
1669         doReturn(credential).when(spyConfig).getCredential();
1670         when(credential.getSimCredential()).thenReturn(null);
1671 
1672         assertFalse(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(spyConfig));
1673     }
1674 
1675     /**
1676      * Verify that if the passpoint profile only have IMSI prefix(mccmnc*) parameter,
1677      * it shouldn't be updated.
1678      */
1679     @Test
tryUpdateCarrierIdForPasspointWithPrefixImsi()1680     public void tryUpdateCarrierIdForPasspointWithPrefixImsi() {
1681         Credential credential = mock(Credential.class);
1682         PasspointConfiguration spyConfig = spy(new PasspointConfiguration());
1683         doReturn(credential).when(spyConfig).getCredential();
1684         Credential.SimCredential simCredential = mock(Credential.SimCredential.class);
1685         when(credential.getSimCredential()).thenReturn(simCredential);
1686         when(simCredential.getImsi()).thenReturn(MATCH_PREFIX_IMSI);
1687 
1688         assertFalse(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(spyConfig));
1689     }
1690 
1691     /**
1692      * Verify that if the passpoint profile has the full IMSI and wasn't assigned valid
1693      * carrier ID, it should be updated.
1694      */
1695     @Test
tryUpdateCarrierIdForPasspointWithFullImsiAndActiveSim()1696     public void tryUpdateCarrierIdForPasspointWithFullImsiAndActiveSim() {
1697         Credential credential = mock(Credential.class);
1698         PasspointConfiguration spyConfig = spy(new PasspointConfiguration());
1699         doReturn(credential).when(spyConfig).getCredential();
1700         Credential.SimCredential simCredential = mock(Credential.SimCredential.class);
1701         when(credential.getSimCredential()).thenReturn(simCredential);
1702         when(simCredential.getImsi()).thenReturn(DATA_FULL_IMSI);
1703 
1704         assertTrue(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(spyConfig));
1705         assertEquals(DATA_CARRIER_ID, spyConfig.getCarrierId());
1706     }
1707 
1708     /**
1709      * Verify that if there is no SIM card matching the given IMSI, it shouldn't be updated.
1710      */
1711     @Test
tryUpdateCarrierIdForPasspointWithFullImsiAndInactiveSim()1712     public void tryUpdateCarrierIdForPasspointWithFullImsiAndInactiveSim() {
1713         Credential credential = mock(Credential.class);
1714         PasspointConfiguration spyConfig = spy(new PasspointConfiguration());
1715         doReturn(credential).when(spyConfig).getCredential();
1716         Credential.SimCredential simCredential = mock(Credential.SimCredential.class);
1717         when(credential.getSimCredential()).thenReturn(simCredential);
1718         when(simCredential.getImsi()).thenReturn(NO_MATCH_PREFIX_IMSI);
1719 
1720         assertFalse(mWifiCarrierInfoManager.tryUpdateCarrierIdForPasspoint(spyConfig));
1721     }
1722 
testIdentityWithSimAndEapAkaMethodPrefix(int method, String methodStr)1723     private void testIdentityWithSimAndEapAkaMethodPrefix(int method, String methodStr)
1724             throws Exception {
1725         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
1726                 .thenReturn(generateTestCarrierConfig(true, true));
1727         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
1728                 .thenReturn(generateTestCarrierConfig(false));
1729         ArgumentCaptor<BroadcastReceiver> receiver =
1730                 ArgumentCaptor.forClass(BroadcastReceiver.class);
1731         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
1732 
1733         receiver.getValue().onReceive(mContext,
1734                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
1735 
1736         assertTrue(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
1737 
1738         String mccmnc = "123456";
1739         String expectedIdentity = methodStr + ANONYMOUS_IDENTITY;
1740         when(mDataTelephonyManager.getSimOperator()).thenReturn(mccmnc);
1741         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
1742                 method, WifiEnterpriseConfig.Phase2.NONE);
1743 
1744         assertEquals(expectedIdentity,
1745                 mWifiCarrierInfoManager.getAnonymousIdentityWith3GppRealm(config));
1746     }
1747 
1748     /**
1749      * Verify that EAP Method prefix is added to the anonymous identity when required
1750      */
1751     @Test
getAnonymousIdentityWithSimAndEapAkaMethodPrefix()1752     public void getAnonymousIdentityWithSimAndEapAkaMethodPrefix() throws Exception {
1753         testIdentityWithSimAndEapAkaMethodPrefix(WifiEnterpriseConfig.Eap.AKA, "0");
1754     }
1755 
1756     /**
1757      * Verify that EAP Method prefix is added to the anonymous identity when required
1758      */
1759     @Test
getAnonymousIdentityWithSimAndEapSimMethodPrefix()1760     public void getAnonymousIdentityWithSimAndEapSimMethodPrefix() throws Exception {
1761         testIdentityWithSimAndEapAkaMethodPrefix(WifiEnterpriseConfig.Eap.SIM, "1");
1762     }
1763 
1764     /**
1765      * Verify that EAP Method prefix is added to the anonymous identity when required
1766      */
1767     @Test
getAnonymousIdentityWithSimAndEapAkaPrimeMethodPrefix()1768     public void getAnonymousIdentityWithSimAndEapAkaPrimeMethodPrefix() throws Exception {
1769         testIdentityWithSimAndEapAkaMethodPrefix(WifiEnterpriseConfig.Eap.AKA_PRIME, "6");
1770     }
1771 
1772     /**
1773      * Verify that isAnonymousAtRealmIdentity works as expected for anonymous identities with and
1774      * without a prefix.
1775      */
1776     @Test
testIsAnonymousAtRealmIdentity()1777     public void testIsAnonymousAtRealmIdentity() throws Exception {
1778         assertTrue(mWifiCarrierInfoManager.isAnonymousAtRealmIdentity(ANONYMOUS_IDENTITY));
1779         assertTrue(mWifiCarrierInfoManager.isAnonymousAtRealmIdentity("0" + ANONYMOUS_IDENTITY));
1780         assertTrue(mWifiCarrierInfoManager.isAnonymousAtRealmIdentity("1" + ANONYMOUS_IDENTITY));
1781         assertTrue(mWifiCarrierInfoManager.isAnonymousAtRealmIdentity("6" + ANONYMOUS_IDENTITY));
1782         assertFalse(mWifiCarrierInfoManager.isAnonymousAtRealmIdentity("AKA" + ANONYMOUS_IDENTITY));
1783     }
1784 
1785     /**
1786      * Verify when no subscription available, get carrier id for target package will return
1787      * UNKNOWN_CARRIER_ID.
1788      */
1789     @Test
getCarrierPrivilegeWithNoActiveSubscription()1790     public void getCarrierPrivilegeWithNoActiveSubscription() {
1791         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
1792         assertEquals(TelephonyManager.UNKNOWN_CARRIER_ID,
1793                 mWifiCarrierInfoManager.getCarrierIdForPackageWithCarrierPrivileges(TEST_PACKAGE));
1794 
1795         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1796                 .thenReturn(Collections.emptyList());
1797         assertEquals(TelephonyManager.UNKNOWN_CARRIER_ID,
1798                 mWifiCarrierInfoManager.getCarrierIdForPackageWithCarrierPrivileges(TEST_PACKAGE));
1799     }
1800 
1801     /**
1802      * Verify when package has no carrier privileges, get carrier id for that package will return
1803      * UNKNOWN_CARRIER_ID.
1804      */
1805     @Test
getCarrierPrivilegeWithPackageHasNoPrivilege()1806     public void getCarrierPrivilegeWithPackageHasNoPrivilege() {
1807         SubscriptionInfo subInfo = mock(SubscriptionInfo.class);
1808         when(subInfo.getSubscriptionId()).thenReturn(DATA_SUBID);
1809         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1810                 .thenReturn(Arrays.asList(subInfo));
1811         when(mDataTelephonyManager.checkCarrierPrivilegesForPackage(TEST_PACKAGE))
1812                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS);
1813         assertEquals(TelephonyManager.UNKNOWN_CARRIER_ID,
1814                 mWifiCarrierInfoManager.getCarrierIdForPackageWithCarrierPrivileges(TEST_PACKAGE));
1815     }
1816 
1817     /**
1818      * Verify when package get carrier privileges from carrier, get carrier id for that package will
1819      * return the carrier id for that carrier.
1820      */
1821     @Test
getCarrierPrivilegeWithPackageHasPrivilege()1822     public void getCarrierPrivilegeWithPackageHasPrivilege() {
1823         SubscriptionInfo subInfo = mock(SubscriptionInfo.class);
1824         when(subInfo.getSubscriptionId()).thenReturn(DATA_SUBID);
1825         when(subInfo.getCarrierId()).thenReturn(DATA_CARRIER_ID);
1826         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1827                 .thenReturn(Arrays.asList(subInfo));
1828         when(mDataTelephonyManager.checkCarrierPrivilegesForPackage(TEST_PACKAGE))
1829                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
1830         assertEquals(DATA_CARRIER_ID,
1831                 mWifiCarrierInfoManager.getCarrierIdForPackageWithCarrierPrivileges(TEST_PACKAGE));
1832     }
1833 
1834     /**
1835      * Verify getCarrierNameForSubId returns right value.
1836      */
1837     @Test
getCarrierNameFromSubId()1838     public void getCarrierNameFromSubId() {
1839         assertEquals(CARRIER_NAME, mWifiCarrierInfoManager.getCarrierNameForSubId(DATA_SUBID));
1840         assertNull(mWifiCarrierInfoManager.getCarrierNameForSubId(NON_DATA_SUBID));
1841     }
1842 
1843     @Test
testIsCarrierNetworkFromNonDataSim()1844     public void testIsCarrierNetworkFromNonDataSim() {
1845         WifiConfiguration config = new WifiConfiguration();
1846         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkFromNonDefaultDataSim(config));
1847         config.carrierId = DATA_CARRIER_ID;
1848         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkFromNonDefaultDataSim(config));
1849         config.carrierId = NON_DATA_CARRIER_ID;
1850         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkFromNonDefaultDataSim(config));
1851     }
1852 
1853     @Test
testCheckSetClearImsiProtectionExemption()1854     public void testCheckSetClearImsiProtectionExemption() {
1855         InOrder inOrder = inOrder(mWifiConfigManager);
1856         assertFalse(mWifiCarrierInfoManager
1857                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
1858         mWifiCarrierInfoManager.setHasUserApprovedImsiPrivacyExemptionForCarrier(true,
1859                 DATA_CARRIER_ID);
1860         verify(mListener).onImsiProtectedOrUserApprovalChanged(DATA_CARRIER_ID, true);
1861         inOrder.verify(mWifiConfigManager).saveToStore();
1862         assertTrue(mWifiCarrierInfoManager
1863                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
1864         mWifiCarrierInfoManager.clearImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID);
1865         inOrder.verify(mWifiConfigManager).saveToStore();
1866         assertFalse(mWifiCarrierInfoManager
1867                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
1868     }
1869 
1870     @Test
testSendImsiProtectionExemptionNotificationWithUserAllowed()1871     public void testSendImsiProtectionExemptionNotificationWithUserAllowed() {
1872         // Setup carrier without IMSI privacy protection
1873         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
1874                 .thenReturn(generateTestCarrierConfig(false));
1875         ArgumentCaptor<BroadcastReceiver> receiver =
1876                 ArgumentCaptor.forClass(BroadcastReceiver.class);
1877         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
1878 
1879         receiver.getValue().onReceive(mContext,
1880                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
1881         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
1882 
1883         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
1884         validateImsiProtectionNotification(CARRIER_NAME);
1885         // Simulate user clicking on allow in the notification.
1886         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_ALLOWED_CARRIER_INTENT_ACTION,
1887                 CARRIER_NAME, DATA_CARRIER_ID);
1888         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
1889         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
1890                 WifiCarrierInfoManager.ACTION_USER_ALLOWED_CARRIER, false);
1891         verify(mWifiConfigManager).saveToStore();
1892         assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
1893         assertTrue(mWifiCarrierInfoManager
1894                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
1895         verify(mListener).onImsiProtectedOrUserApprovalChanged(DATA_CARRIER_ID, true);
1896         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
1897                 WifiCarrierInfoManager.ACTION_USER_ALLOWED_CARRIER, false);
1898     }
1899 
1900     @Test
testSendImsiProtectionExemptionNotificationWithUserDisallowed()1901     public void testSendImsiProtectionExemptionNotificationWithUserDisallowed() {
1902         // Setup carrier without IMSI privacy protection
1903         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
1904                 .thenReturn(generateTestCarrierConfig(false));
1905         ArgumentCaptor<BroadcastReceiver> receiver =
1906                 ArgumentCaptor.forClass(BroadcastReceiver.class);
1907         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
1908 
1909         receiver.getValue().onReceive(mContext,
1910                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
1911         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
1912 
1913         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
1914         validateImsiProtectionNotification(CARRIER_NAME);
1915         // Simulate user clicking on disallow in the notification.
1916         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_DISALLOWED_CARRIER_INTENT_ACTION,
1917                 CARRIER_NAME, DATA_CARRIER_ID);
1918         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
1919         verify(mDialogHandle, never()).launchDialog();
1920 
1921         verify(mWifiConfigManager).saveToStore();
1922         assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
1923         assertFalse(mWifiCarrierInfoManager
1924                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
1925         verify(mListener, never())
1926                 .onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
1927         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
1928                 WifiCarrierInfoManager.ACTION_USER_DISALLOWED_CARRIER, false);
1929     }
1930 
1931     @Test
testSendImsiProtectionExemptionNotificationWithUserDismissal()1932     public void testSendImsiProtectionExemptionNotificationWithUserDismissal() {
1933         // Setup carrier without IMSI privacy protection
1934         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
1935                 .thenReturn(generateTestCarrierConfig(false));
1936         ArgumentCaptor<BroadcastReceiver> receiver =
1937                 ArgumentCaptor.forClass(BroadcastReceiver.class);
1938         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
1939 
1940         receiver.getValue().onReceive(mContext,
1941                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
1942         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
1943 
1944         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
1945         validateImsiProtectionNotification(CARRIER_NAME);
1946         //Simulate user dismissal the notification
1947         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_DISMISSED_INTENT_ACTION,
1948                 CARRIER_NAME, DATA_CARRIER_ID);
1949         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
1950                 WifiCarrierInfoManager.ACTION_USER_DISMISS, false);
1951         reset(mWifiNotificationManager);
1952         // No Notification is active, should send notification again.
1953         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
1954         verifyNoMoreInteractions(mWifiNotificationManager);
1955 
1956         when(mClock.getElapsedSinceBootMillis()).thenReturn(mCurrentTimeMills + 6 * 60 * 1000);
1957         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
1958         validateImsiProtectionNotification(CARRIER_NAME);
1959         reset(mWifiNotificationManager);
1960 
1961         // As there is notification is active, should not send notification again.
1962         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_DISMISSED_INTENT_ACTION,
1963                 CARRIER_NAME, DATA_CARRIER_ID);
1964         verifyNoMoreInteractions(mWifiNotificationManager);
1965         verify(mWifiConfigManager, never()).saveToStore();
1966         assertFalse(mCarrierInfoDataSource.hasNewDataToSerialize());
1967         assertFalse(mWifiCarrierInfoManager
1968                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
1969         verify(mListener, never())
1970                 .onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
1971     }
1972 
1973     @Test
testSendImsiProtectionExemptionConfirmationDialogWithUserDisallowed()1974     public void testSendImsiProtectionExemptionConfirmationDialogWithUserDisallowed() {
1975         // Setup carrier without IMSI privacy protection
1976         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
1977                 .thenReturn(generateTestCarrierConfig(false));
1978         ArgumentCaptor<BroadcastReceiver> receiver =
1979                 ArgumentCaptor.forClass(BroadcastReceiver.class);
1980         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
1981 
1982         receiver.getValue().onReceive(mContext,
1983                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
1984         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
1985 
1986         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
1987         validateImsiProtectionNotification(CARRIER_NAME);
1988         // Simulate user clicking on the notification.
1989         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_CLICKED_INTENT_ACTION,
1990                 CARRIER_NAME, DATA_CARRIER_ID);
1991         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
1992         validateUserApprovalDialog(CARRIER_NAME);
1993 
1994         // Simulate user clicking on disallow in the dialog.
1995         ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> dialogCallbackCaptor =
1996                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
1997         verify(mWifiDialogManager).createSimpleDialog(
1998                 any(), any(), any(), any(), any(), dialogCallbackCaptor.capture(), any());
1999         dialogCallbackCaptor.getValue().onNegativeButtonClicked();
2000         ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
2001         verify(mContext).sendBroadcast(intentCaptor.capture(), any(), any());
2002         assertEquals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, intentCaptor.getValue().getAction());
2003         verify(mWifiConfigManager).saveToStore();
2004         assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
2005         assertFalse(mWifiCarrierInfoManager
2006                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
2007         verify(mListener, never())
2008                 .onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
2009         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
2010                 WifiCarrierInfoManager.ACTION_USER_DISALLOWED_CARRIER, true);
2011     }
2012 
2013     @Test
testSendImsiProtectionExemptionConfirmationDialogWithUserDismissal()2014     public void testSendImsiProtectionExemptionConfirmationDialogWithUserDismissal() {
2015         // Setup carrier without IMSI privacy protection
2016         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
2017                 .thenReturn(generateTestCarrierConfig(false));
2018         ArgumentCaptor<BroadcastReceiver> receiver =
2019                 ArgumentCaptor.forClass(BroadcastReceiver.class);
2020         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
2021 
2022         receiver.getValue().onReceive(mContext,
2023                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
2024         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
2025 
2026         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2027         validateImsiProtectionNotification(CARRIER_NAME);
2028         // Simulate user clicking on the notification.
2029         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_CLICKED_INTENT_ACTION,
2030                 CARRIER_NAME, DATA_CARRIER_ID);
2031         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
2032         validateUserApprovalDialog(CARRIER_NAME);
2033 
2034         // Simulate user dismissing the dialog via home/back button.
2035         ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> dialogCallbackCaptor =
2036                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
2037         verify(mWifiDialogManager).createSimpleDialog(
2038                 any(), any(), any(), any(), any(), dialogCallbackCaptor.capture(), any());
2039         dialogCallbackCaptor.getValue().onCancelled();
2040         ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
2041         verify(mContext).sendBroadcast(intentCaptor.capture(), any(), any());
2042         assertEquals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, intentCaptor.getValue().getAction());
2043 
2044         // As user dismissed the notification, there will be a certain time to delay the next
2045         // notification
2046         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2047         verifyNoMoreInteractions(mWifiNotificationManager);
2048 
2049         when(mClock.getElapsedSinceBootMillis()).thenReturn(mCurrentTimeMills + 6 * 60 * 1000);
2050         validateImsiProtectionNotification(CARRIER_NAME);
2051 
2052         verify(mWifiConfigManager, never()).saveToStore();
2053         assertFalse(mCarrierInfoDataSource.hasNewDataToSerialize());
2054         assertFalse(mWifiCarrierInfoManager
2055                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
2056         verify(mListener, never())
2057                 .onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
2058         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
2059                 WifiCarrierInfoManager.ACTION_USER_DISMISS, true);
2060     }
2061 
2062     @Test
testSendImsiProtectionExemptionDialogWithUserAllowed()2063     public void testSendImsiProtectionExemptionDialogWithUserAllowed() {
2064         // Setup carrier without IMSI privacy protection
2065         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
2066                 .thenReturn(generateTestCarrierConfig(false));
2067         ArgumentCaptor<BroadcastReceiver> receiver =
2068                 ArgumentCaptor.forClass(BroadcastReceiver.class);
2069         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
2070 
2071         receiver.getValue().onReceive(mContext,
2072                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
2073         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
2074 
2075         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2076         validateImsiProtectionNotification(CARRIER_NAME);
2077         // Simulate user clicking on the notification.
2078         sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_CLICKED_INTENT_ACTION,
2079                 CARRIER_NAME, DATA_CARRIER_ID);
2080         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
2081         validateUserApprovalDialog(CARRIER_NAME);
2082 
2083         // Simulate user clicking on allow in the dialog.
2084         ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> dialogCallbackCaptor =
2085                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
2086         verify(mWifiDialogManager).createSimpleDialog(
2087                 any(), any(), any(), any(), any(), dialogCallbackCaptor.capture(), any());
2088         dialogCallbackCaptor.getValue().onPositiveButtonClicked();
2089         ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
2090         verify(mContext).sendBroadcast(intentCaptor.capture(), any(), any());
2091         assertEquals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, intentCaptor.getValue().getAction());
2092         verify(mWifiConfigManager).saveToStore();
2093         assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
2094         verify(mListener).onImsiProtectedOrUserApprovalChanged(DATA_CARRIER_ID, true);
2095         verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
2096                 WifiCarrierInfoManager.ACTION_USER_ALLOWED_CARRIER, true);
2097     }
2098 
2099     @Test
testUserDataStoreIsNotLoadedNotificationWillNotBeSent()2100     public void testUserDataStoreIsNotLoadedNotificationWillNotBeSent() {
2101         // reset data source to unloaded state.
2102         mImsiDataSource.reset();
2103         // Setup carrier without IMSI privacy protection
2104         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
2105                 .thenReturn(generateTestCarrierConfig(false));
2106         ArgumentCaptor<BroadcastReceiver> receiver =
2107                 ArgumentCaptor.forClass(BroadcastReceiver.class);
2108         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
2109 
2110         receiver.getValue().onReceive(mContext,
2111                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
2112         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
2113 
2114         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2115         verifyNoMoreInteractions(mWifiNotificationManager);
2116 
2117         // Loaded user data store, notification should be sent
2118         mImsiDataSource.fromDeserialized(new HashMap<>());
2119         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2120         validateImsiProtectionNotification(CARRIER_NAME);
2121     }
2122 
2123     @Test
testCarrierConfigNotAvailableNotificationWillNotBeSent()2124     public void testCarrierConfigNotAvailableNotificationWillNotBeSent() {
2125         // Setup carrier without IMSI privacy protection
2126         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
2127                 .thenReturn(generateTestCarrierConfig(false));
2128         ArgumentCaptor<BroadcastReceiver> receiver =
2129                 ArgumentCaptor.forClass(BroadcastReceiver.class);
2130         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
2131 
2132         receiver.getValue().onReceive(mContext,
2133                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
2134         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
2135         // Carrier config for Non data carrier is not available, no notification will send.
2136         mWifiCarrierInfoManager
2137                 .sendImsiProtectionExemptionNotificationIfRequired(NON_DATA_CARRIER_ID);
2138         verifyNoMoreInteractions(mWifiNotificationManager);
2139 
2140         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2141         validateImsiProtectionNotification(CARRIER_NAME);
2142     }
2143 
2144     @Test
testImsiProtectionExemptionNotificationNotSentWhenCarrierNameIsInvalid()2145     public void testImsiProtectionExemptionNotificationNotSentWhenCarrierNameIsInvalid() {
2146         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID))
2147                 .thenReturn(generateTestCarrierConfig(false));
2148         ArgumentCaptor<BroadcastReceiver> receiver =
2149                 ArgumentCaptor.forClass(BroadcastReceiver.class);
2150         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
2151 
2152         receiver.getValue().onReceive(mContext,
2153                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
2154         assertFalse(mWifiCarrierInfoManager.requiresImsiEncryption(DATA_SUBID));
2155         when(mDataTelephonyManager.getSimCarrierIdName()).thenReturn(null);
2156         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(DATA_CARRIER_ID);
2157         verify(mWifiNotificationManager, never()).notify(
2158                 eq(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE),
2159                 eq(mNotification));
2160 
2161     }
2162 
2163     @Test
testImsiProtectionExemptionNotificationNotSentWhenOobPseudonymEnabled()2164     public void testImsiProtectionExemptionNotificationNotSentWhenOobPseudonymEnabled() {
2165         // NON_DATA_SUBID enabled the OOB pseudonym.
2166         when(mCarrierConfigManager.getConfigForSubId(NON_DATA_SUBID))
2167                 .thenReturn(generateTestCarrierConfig(false));
2168         mWifiCarrierInfoManager.sendImsiProtectionExemptionNotificationIfRequired(
2169                 NON_DATA_CARRIER_ID);
2170         verify(mWifiNotificationManager, never()).notify(
2171                 eq(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE),
2172                 eq(mNotification));
2173     }
2174 
2175     @Test
verifySubIdAndCarrierIdMatching()2176     public void verifySubIdAndCarrierIdMatching() {
2177         assertTrue(mWifiCarrierInfoManager.isSubIdMatchingCarrierId(
2178                 SubscriptionManager.INVALID_SUBSCRIPTION_ID, DATA_CARRIER_ID));
2179         assertFalse(mWifiCarrierInfoManager.isSubIdMatchingCarrierId(
2180                 DATA_SUBID, TelephonyManager.UNKNOWN_CARRIER_ID));
2181 
2182         assertTrue(mWifiCarrierInfoManager.isSubIdMatchingCarrierId(
2183                 DATA_SUBID, DATA_CARRIER_ID));
2184         assertFalse(mWifiCarrierInfoManager.isSubIdMatchingCarrierId(
2185                 NON_DATA_SUBID, DATA_CARRIER_ID));
2186     }
2187 
2188     @Test
testSetAndGetUnmergedCarrierNetworkOffload()2189     public void testSetAndGetUnmergedCarrierNetworkOffload() {
2190         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, false));
2191         mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(DATA_SUBID, false, false);
2192         mLooper.dispatchAll();
2193         verify(mWifiConfigManager).saveToStore();
2194         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, false));
2195     }
2196 
2197     @Test
testSetAndGetMergedCarrierNetworkOffload()2198     public void testSetAndGetMergedCarrierNetworkOffload() {
2199         assumeTrue(SdkLevel.isAtLeastS());
2200         when(mDataTelephonyManager.isDataEnabled()).thenReturn(true);
2201         ArgumentCaptor<WifiCarrierInfoManager.UserDataEnabledChangedListener> listenerCaptor =
2202                 ArgumentCaptor.forClass(
2203                         WifiCarrierInfoManager.UserDataEnabledChangedListener.class);
2204         // Check default value and verify listen is registered.
2205         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
2206         verify(mDataTelephonyManager).registerTelephonyCallback(any(), listenerCaptor.capture());
2207 
2208         // Verify result will change with state changes
2209         listenerCaptor.getValue().onDataEnabledChanged(false, DATA_ENABLED_REASON_THERMAL);
2210         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
2211 
2212         listenerCaptor.getValue().onDataEnabledChanged(true, DATA_ENABLED_REASON_USER);
2213         mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(DATA_SUBID, true, false);
2214         mLooper.dispatchAll();
2215         verify(mWifiConfigManager).saveToStore();
2216         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
2217 
2218     }
2219 
validateImsiProtectionNotification(String carrierName)2220     private void validateImsiProtectionNotification(String carrierName) {
2221         verify(mWifiNotificationManager, atLeastOnce()).notify(
2222                 eq(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE),
2223                 eq(mNotification));
2224         ArgumentCaptor<CharSequence> contentCaptor =
2225                 ArgumentCaptor.forClass(CharSequence.class);
2226         verify(mNotificationBuilder, atLeastOnce()).setContentTitle(contentCaptor.capture());
2227         CharSequence content = contentCaptor.getValue();
2228         assertNotNull(content);
2229         assertTrue(content.toString().contains(carrierName));
2230     }
2231 
validateUserApprovalDialog(String... anyOfExpectedAppNames)2232     private void validateUserApprovalDialog(String... anyOfExpectedAppNames) {
2233         verify(mDialogHandle, atLeastOnce()).launchDialog();
2234         ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
2235         verify(mWifiDialogManager, atLeastOnce()).createSimpleDialog(
2236                 any(), messageCaptor.capture(), any(), any(), any(), any(), any());
2237         String message = messageCaptor.getValue();
2238         assertNotNull(message);
2239 
2240         boolean foundMatch = false;
2241         for (int i = 0; i < anyOfExpectedAppNames.length; i++) {
2242             foundMatch = message.contains(anyOfExpectedAppNames[i]);
2243             if (foundMatch) break;
2244         }
2245         assertTrue(foundMatch);
2246     }
2247 
sendBroadcastForUserActionOnImsi(String action, String carrierName, int carrierId)2248     private void sendBroadcastForUserActionOnImsi(String action, String carrierName,
2249             int carrierId) {
2250         Intent intent = new Intent()
2251                 .setAction(action)
2252                 .putExtra(WifiCarrierInfoManager.EXTRA_CARRIER_NAME, carrierName)
2253                 .putExtra(WifiCarrierInfoManager.EXTRA_CARRIER_ID, carrierId);
2254         assertNotNull(mBroadcastReceiverCaptor.getValue());
2255         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
2256     }
2257 
2258     @Test
testSendRefreshUserProvisioningOnUnlockedUserSwitching()2259     public void testSendRefreshUserProvisioningOnUnlockedUserSwitching() {
2260         PackageManager mockPackageManager = mock(PackageManager.class);
2261         when(mContext.getPackageManager()).thenReturn(mockPackageManager);
2262         PackageInfo pi = new PackageInfo();
2263         pi.packageName = "com.example.app";
2264         List<PackageInfo> pis = List.of(pi);
2265         when(mockPackageManager.getPackagesHoldingPermissions(
2266                 eq(new String[] {android.Manifest.permission.NETWORK_CARRIER_PROVISIONING}),
2267                 anyInt())).thenReturn(pis);
2268 
2269         mWifiCarrierInfoManager.onUnlockedUserSwitching(1);
2270 
2271         ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
2272         verify(mContext).sendBroadcastAsUser(
2273                 intentCaptor.capture(),
2274                 eq(UserHandle.CURRENT),
2275                 eq(android.Manifest.permission.NETWORK_CARRIER_PROVISIONING));
2276         Intent intent = intentCaptor.getValue();
2277         assertEquals(intent.getAction(), WifiManager.ACTION_REFRESH_USER_PROVISIONING);
2278     }
2279 
2280     /**
2281      * Verify that shouldDisableMacRandomization returns true if the SSID in the input config
2282      * matches with the SSID list in CarrierConfigManager.
2283      */
2284     @Test
testShouldDisableMacRandomization()2285     public void testShouldDisableMacRandomization() {
2286         // Create 2 WifiConfigurations and mock CarrierConfigManager to include the SSID
2287         // of the first one in the MAC randomization disabled list.
2288         WifiConfiguration config1 = WifiConfigurationTestUtil.createOpenNetwork();
2289         WifiConfiguration config2 = WifiConfigurationTestUtil.createOpenNetwork();
2290         config1.carrierId = DATA_CARRIER_ID;
2291         config1.subscriptionId = DATA_SUBID;
2292         PersistableBundle bundle = new PersistableBundle();
2293         PersistableBundle wifiBundle = new PersistableBundle();
2294         // Add the first SSID and some garbage SSID to the exception list.
2295         wifiBundle.putStringArray(
2296                 CarrierConfigManager.Wifi.KEY_SUGGESTION_SSID_LIST_WITH_MAC_RANDOMIZATION_DISABLED,
2297                 new String[]{
2298                         WifiInfo.sanitizeSsid(config1.SSID),
2299                         WifiInfo.sanitizeSsid(config2.SSID) + "_GARBAGE"});
2300         wifiBundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
2301         bundle.putAll(wifiBundle);
2302         when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(bundle);
2303 
2304         if (SdkLevel.isAtLeastS()) {
2305             // Verify MAC randomization is disable for config1, but not disabled for config2
2306             assertFalse(mWifiCarrierInfoManager.shouldDisableMacRandomization(config2.SSID,
2307                     config2.carrierId, config2.subscriptionId));
2308             assertTrue(mWifiCarrierInfoManager.shouldDisableMacRandomization(config1.SSID,
2309                     config1.carrierId, config1.subscriptionId));
2310 
2311             // Verify getConfigForSubId is only called once since the CarrierConfig gets cached.
2312             verify(mCarrierConfigManager).getConfigForSubId(anyInt());
2313         } else {
2314             // Verify MAC randomization is not disabled for either configuration.
2315             assertFalse(mWifiCarrierInfoManager.shouldDisableMacRandomization(config2.SSID,
2316                     config2.carrierId, config2.subscriptionId));
2317             assertFalse(mWifiCarrierInfoManager.shouldDisableMacRandomization(config1.SSID,
2318                     config1.carrierId, config1.subscriptionId));
2319         }
2320     }
2321 
2322     /**
2323      * Verify that shouldDisableMacRandomization returns false if the carrierId is not set.
2324      */
2325     @Test
testOnlyDisableMacRandomizationOnCarrierNetworks()2326     public void testOnlyDisableMacRandomizationOnCarrierNetworks() {
2327         // Create 2 WifiConfiguration, but only set the carrierId for the first config.
2328         WifiConfiguration config1 = WifiConfigurationTestUtil.createOpenNetwork();
2329         WifiConfiguration config2 = WifiConfigurationTestUtil.createOpenNetwork();
2330         config1.carrierId = DATA_CARRIER_ID;
2331         config1.subscriptionId = DATA_SUBID;
2332         PersistableBundle bundle = new PersistableBundle();
2333         PersistableBundle wifiBundle = new PersistableBundle();
2334         // add both the first SSID and second SSID to the exception list.
2335         wifiBundle.putStringArray(
2336                 CarrierConfigManager.Wifi.KEY_SUGGESTION_SSID_LIST_WITH_MAC_RANDOMIZATION_DISABLED,
2337                 new String[]{
2338                         WifiInfo.sanitizeSsid(config1.SSID),
2339                         WifiInfo.sanitizeSsid(config2.SSID)});
2340         wifiBundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
2341         bundle.putAll(wifiBundle);
2342         when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(bundle);
2343 
2344         if (SdkLevel.isAtLeastS()) {
2345             // Verify MAC randomization is disable for config1, but not disabled for config2
2346             assertTrue(mWifiCarrierInfoManager.shouldDisableMacRandomization(config1.SSID,
2347                     config1.carrierId, config1.subscriptionId));
2348             assertFalse(mWifiCarrierInfoManager.shouldDisableMacRandomization(config2.SSID,
2349                     config2.carrierId, config2.subscriptionId));
2350             // Verify getConfigForSubId is only called once since the CarrierConfig gets cached.
2351             verify(mCarrierConfigManager).getConfigForSubId(anyInt());
2352         } else {
2353             // Verify MAC randomization is not disabled for either configuration.
2354             assertFalse(mWifiCarrierInfoManager.shouldDisableMacRandomization(config1.SSID,
2355                     config1.carrierId, config1.subscriptionId));
2356             assertFalse(mWifiCarrierInfoManager.shouldDisableMacRandomization(config2.SSID,
2357                     config2.carrierId, config2.subscriptionId));
2358         }
2359     }
2360 
2361     @Test
testAllowCarrierWifiForCarrier()2362     public void testAllowCarrierWifiForCarrier() {
2363         PersistableBundle bundle = new PersistableBundle();
2364         bundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
2365         String key = CarrierConfigManager.KEY_CARRIER_PROVISIONS_WIFI_MERGED_NETWORKS_BOOL;
2366         int subId = DATA_SUBID;
2367         when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(bundle);
2368 
2369         if (SdkLevel.isAtLeastS()) {
2370             // not allowed: false
2371             bundle.putBoolean(key, false);
2372             assertFalse(
2373                     mWifiCarrierInfoManager.areMergedCarrierWifiNetworksAllowed(subId));
2374 
2375             // allowed: true
2376             bundle.putBoolean(key, true);
2377             assertTrue(
2378                     mWifiCarrierInfoManager.areMergedCarrierWifiNetworksAllowed(subId));
2379 
2380             // no key
2381             bundle.clear();
2382             assertFalse(
2383                     mWifiCarrierInfoManager.areMergedCarrierWifiNetworksAllowed(subId));
2384         } else {
2385             assertFalse(
2386                     mWifiCarrierInfoManager.areMergedCarrierWifiNetworksAllowed(subId));
2387         }
2388     }
2389 
2390     @Test
testResetNotification()2391     public void testResetNotification() {
2392         mWifiCarrierInfoManager.resetNotification();
2393         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
2394     }
2395 
2396     @Test
testClear()2397     public void testClear() {
2398         when(mDataTelephonyManager.isDataEnabled()).thenReturn(true);
2399         mWifiCarrierInfoManager.setHasUserApprovedImsiPrivacyExemptionForCarrier(
2400                 true, DATA_CARRIER_ID);
2401         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
2402         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(NON_DATA_SUBID, false));
2403         mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(DATA_SUBID, true, false);
2404         mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(NON_DATA_SUBID, false, false);
2405         // Verify values.
2406         assertTrue(mWifiCarrierInfoManager
2407                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
2408         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
2409         assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(NON_DATA_SUBID, false));
2410         // Now clear everything.
2411         mWifiCarrierInfoManager.clear();
2412 
2413         verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
2414         if (SdkLevel.isAtLeastS()) {
2415             verify(mDataTelephonyManager).unregisterTelephonyCallback(any());
2416         }
2417 
2418         // Verify restore to default value.
2419         assertFalse(mWifiCarrierInfoManager
2420                 .hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
2421         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
2422         assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(NON_DATA_SUBID, false));
2423 
2424         // Verify active subscription info is not clear
2425         assertEquals(DATA_SUBID, mWifiCarrierInfoManager.getMatchingSubId(DATA_CARRIER_ID));
2426     }
2427 
2428     @Test
testOnCarrierOffloadDisabledListener()2429     public void testOnCarrierOffloadDisabledListener() {
2430         assumeTrue(SdkLevel.isAtLeastS());
2431         mWifiCarrierInfoManager.addOnCarrierOffloadDisabledListener(
2432                 mOnCarrierOffloadDisabledListener);
2433         mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true);
2434         ArgumentCaptor<WifiCarrierInfoManager.UserDataEnabledChangedListener> captor =
2435                 ArgumentCaptor.forClass(WifiCarrierInfoManager.UserDataEnabledChangedListener
2436                         .class);
2437         verify(mDataTelephonyManager).registerTelephonyCallback(any(), captor.capture());
2438 
2439         mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(DATA_SUBID, true, false);
2440         mLooper.dispatchAll();
2441         verify(mOnCarrierOffloadDisabledListener).onCarrierOffloadDisabled(DATA_SUBID, true);
2442 
2443         captor.getValue().onDataEnabledChanged(false, DATA_ENABLED_REASON_CARRIER);
2444         verify(mOnCarrierOffloadDisabledListener, times(2))
2445                 .onCarrierOffloadDisabled(DATA_SUBID, true);
2446     }
2447 
2448     @Test
testGetActiveSubsctionIdInGroup()2449     public void testGetActiveSubsctionIdInGroup() {
2450         assertEquals(DATA_SUBID, mWifiCarrierInfoManager
2451                 .getActiveSubscriptionIdInGroup(GROUP_UUID));
2452     }
2453 
2454     @Test
testCarrierPrivilegedListenerChange()2455     public void testCarrierPrivilegedListenerChange() {
2456         assumeTrue(SdkLevel.isAtLeastT());
2457         TelephonyManager.CarrierPrivilegesCallback carrierPrivilegesCallback;
2458         ArgumentCaptor<TelephonyManager.CarrierPrivilegesCallback> callbackArgumentCaptor =
2459                 ArgumentCaptor.forClass(TelephonyManager.CarrierPrivilegesCallback.class);
2460         verify(mTelephonyManager, times(2))
2461                 .registerCarrierPrivilegesCallback(anyInt(), any(),
2462                         callbackArgumentCaptor.capture());
2463         carrierPrivilegesCallback = callbackArgumentCaptor.getValue();
2464         carrierPrivilegesCallback.onCarrierPrivilegesChanged(Collections.emptySet(),
2465                 Collections.emptySet());
2466         verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps(any());
2467     }
2468 
2469     @Test
testGetMatchingSubId()2470     public void testGetMatchingSubId() {
2471         ArgumentCaptor<BroadcastReceiver> receiver =
2472                 ArgumentCaptor.forClass(BroadcastReceiver.class);
2473         verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
2474 
2475         // Make two subscription from same carrier
2476         when(mDataSubscriptionInfo.getCarrierId()).thenReturn(DATA_CARRIER_ID);
2477         when(mDataSubscriptionInfo.getSubscriptionId()).thenReturn(DATA_SUBID);
2478         when(mNonDataSubscriptionInfo.getCarrierId()).thenReturn(DATA_CARRIER_ID);
2479         when(mNonDataSubscriptionInfo.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
2480         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2481 
2482         // Data sim should be selected
2483         assertEquals(DATA_SUBID, mWifiCarrierInfoManager.getMatchingSubId(DATA_CARRIER_ID));
2484 
2485         // Disable data sim.
2486         when(mCarrierConfigManager.getConfigForSubId(DATA_SUBID)).thenReturn(null);
2487         receiver.getValue().onReceive(mContext,
2488                 new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
2489         mLooper.dispatchAll();
2490         // Non-data sim should be selected
2491         assertEquals(NON_DATA_SUBID, mWifiCarrierInfoManager.getMatchingSubId(DATA_CARRIER_ID));
2492     }
2493 
2494     @Test
testIsOobPseudonymFeatureEnabled_phFlagDisabled()2495     public void testIsOobPseudonymFeatureEnabled_phFlagDisabled() {
2496         when(mDeviceConfigFacade.isOobPseudonymEnabled()).thenReturn(false);
2497 
2498         assertFalse(mWifiCarrierInfoManager.isOobPseudonymFeatureEnabled(123));
2499     }
2500 
2501     @Test
testIsOobPseudonymFeatureEnabled_resourceOverrideAsTrue()2502     public void testIsOobPseudonymFeatureEnabled_resourceOverrideAsTrue() {
2503         when(mDeviceConfigFacade.isOobPseudonymEnabled()).thenReturn(true);
2504         when(mWifiStringResourceWrapper.getBoolean(
2505                 eq(WifiCarrierInfoManager.CONFIG_WIFI_OOB_PSEUDONYM_ENABLED), anyBoolean()))
2506                 .thenReturn(true);
2507 
2508         assertTrue(mWifiCarrierInfoManager.isOobPseudonymFeatureEnabled(1));
2509     }
2510 
2511     @Test
testActiveSubsChangeUpdateWifiNetworkFactory()2512     public void testActiveSubsChangeUpdateWifiNetworkFactory() {
2513         SubscriptionInfo subInfo1 = mock(SubscriptionInfo.class);
2514         when(subInfo1.getSubscriptionId()).thenReturn(DATA_SUBID);
2515         SubscriptionInfo subInfo2 = mock(SubscriptionInfo.class);
2516         when(subInfo2.getSubscriptionId()).thenReturn(NON_DATA_SUBID);
2517         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
2518                 .thenReturn(Arrays.asList(subInfo1, subInfo2));
2519         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2520         mLooper.dispatchAll();
2521         ArgumentCaptor<Set<Integer>> restrictedWifiCaptor = ArgumentCaptor.forClass(Set.class);
2522         ArgumentCaptor<Set<Integer>> untrustedWifiCaptor = ArgumentCaptor.forClass(Set.class);
2523         ArgumentCaptor<Set<Integer>> wifiCaptor = ArgumentCaptor.forClass(Set.class);
2524         verify(mRestrictedWifiNetworkFactory, times(2)).updateSubIdsInCapabilitiesFilter(
2525                 restrictedWifiCaptor.capture());
2526         assertThat(restrictedWifiCaptor.getValue()).containsExactly(DATA_SUBID, NON_DATA_SUBID);
2527         verify(mUntrustedWifiNetworkFactory, times(2)).updateSubIdsInCapabilitiesFilter(
2528                 untrustedWifiCaptor.capture());
2529         assertThat(restrictedWifiCaptor.getValue()).containsExactly(DATA_SUBID, NON_DATA_SUBID);
2530         verify(mWifiNetworkFactory, times(2)).updateSubIdsInCapabilitiesFilter(
2531                 wifiCaptor.capture());
2532         assertThat(wifiCaptor.getValue()).containsExactly(DATA_SUBID, NON_DATA_SUBID);
2533     }
2534 
2535     @Test
isMobileDataEnabled_true()2536     public void isMobileDataEnabled_true() {
2537         assumeTrue(SdkLevel.isAtLeastS());
2538         when(mDataTelephonyManager.isDataEnabled()).thenReturn(true);
2539         assertTrue(mWifiCarrierInfoManager.isMobileDataEnabled());
2540     }
2541 
2542     @Test
isMobileDataEnabled_false_null()2543     public void isMobileDataEnabled_false_null() {
2544         assumeTrue(SdkLevel.isAtLeastS());
2545         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
2546                 .thenReturn(null);
2547         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2548         mLooper.dispatchAll();
2549 
2550         assertFalse(mWifiCarrierInfoManager.isMobileDataEnabled());
2551     }
2552     @Test
isMobileDataEnabled_false_empty()2553     public void isMobileDataEnabled_false_empty() {
2554         assumeTrue(SdkLevel.isAtLeastS());
2555         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
2556                 .thenReturn(new ArrayList<>());
2557         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2558         mLooper.dispatchAll();
2559 
2560         assertFalse(mWifiCarrierInfoManager.isMobileDataEnabled());
2561     }
2562 
2563     @Test
isMobileDataEnabled_false_present()2564     public void isMobileDataEnabled_false_present() {
2565         assumeTrue(SdkLevel.isAtLeastS());
2566         when(mDataTelephonyManager.isDataEnabled()).thenReturn(false);
2567         when(mNonDataTelephonyManager.isDataEnabled()).thenReturn(false);
2568         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2569         mLooper.dispatchAll();
2570 
2571         assertFalse(mWifiCarrierInfoManager.isMobileDataEnabled());
2572     }
2573 
2574     @Test
hasActiveSubInfo_true()2575     public void hasActiveSubInfo_true() {
2576         assertTrue(mWifiCarrierInfoManager.hasActiveSubInfo());
2577     }
2578 
2579     @Test
hasActiveSubInfo_false_null()2580     public void hasActiveSubInfo_false_null() {
2581         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
2582         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2583         mLooper.dispatchAll();
2584 
2585         assertFalse(mWifiCarrierInfoManager.hasActiveSubInfo());
2586     }
2587 
2588     @Test
hasActiveSubInfo_false_empty()2589     public void hasActiveSubInfo_false_empty() {
2590         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
2591                 .thenReturn(new ArrayList<>());
2592         mListenerArgumentCaptor.getValue().onSubscriptionsChanged();
2593         mLooper.dispatchAll();
2594 
2595         assertFalse(mWifiCarrierInfoManager.hasActiveSubInfo());
2596     }
2597 }
2598