summaryrefslogtreecommitdiff
path: root/tests/tests/vcn/src/android/net/vcn/cts/VcnManagerTest.java
blob: 7d13fea0b2cbb43dc88b61d7659b52ef6c6f77d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.vcn.cts;

import static android.content.pm.PackageManager.FEATURE_TELEPHONY;
import static android.content.pm.PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION;
import static android.ipsec.ike.cts.IkeTunUtils.PortPair;
import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
import static android.net.ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
import static android.net.ConnectivitySettingsManager.getCaptivePortalMode;
import static android.net.ConnectivitySettingsManager.setCaptivePortalMode;
import static android.net.NetworkCapabilities.NET_CAPABILITY_CBS;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_RCS;
import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
import static android.net.NetworkCapabilities.TRANSPORT_TEST;
import static android.net.vcn.VcnGatewayConnectionConfig.VCN_GATEWAY_OPTION_ENABLE_DATA_STALL_RECOVERY_WITH_MOBILITY;
import static android.net.vcn.VcnManager.VCN_STATUS_CODE_ACTIVE;
import static android.net.vcn.VcnManager.VCN_STATUS_CODE_NOT_CONFIGURED;
import static android.net.vcn.VcnManager.VCN_STATUS_CODE_SAFE_MODE;
import static android.net.vcn.VcnUnderlyingNetworkTemplate.MATCH_ANY;
import static android.net.vcn.VcnUnderlyingNetworkTemplate.MATCH_FORBIDDEN;
import static android.net.vcn.VcnUnderlyingNetworkTemplate.MATCH_REQUIRED;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;

import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;

import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
import static com.android.compatibility.common.util.TestUtils.waitUntil;
import static com.android.internal.util.HexDump.hexStringToByteArray;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.content.pm.PackageManager;
import android.ipsec.ike.cts.IkeTunUtils;
import android.net.ConnectivityManager;
import android.net.InetAddresses;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.vcn.Flags;
import android.net.vcn.VcnCellUnderlyingNetworkTemplate;
import android.net.vcn.VcnConfig;
import android.net.vcn.VcnGatewayConnectionConfig;
import android.net.vcn.VcnManager;
import android.net.vcn.VcnNetworkPolicyResult;
import android.net.vcn.VcnUnderlyingNetworkTemplate;
import android.net.vcn.VcnWifiUnderlyingNetworkTemplate;
import android.net.vcn.cts.TestNetworkWrapper.VcnTestNetworkCallback;
import android.net.vcn.cts.TestNetworkWrapper.VcnTestNetworkCallback.CapabilitiesChangedEvent;
import android.os.ParcelUuid;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.platform.test.annotations.RequiresFlagsEnabled;
import android.platform.test.flag.junit.CheckFlagsRule;
import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.cts.util.SubscriptionGroupUtils;

import androidx.test.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import com.android.compatibility.common.util.CarrierPrivilegeUtils;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@RunWith(AndroidJUnit4.class)
public class VcnManagerTest extends VcnTestBase {
    @Rule
    public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();

    private static final String TAG = VcnManagerTest.class.getSimpleName();

    private static final int TIMEOUT_MS = 500;
    private static final long SAFEMODE_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(35);

    private static final int ACTIVE_SUB_ID_TIMEOUT_SECONDS = 60;

    private static final Executor INLINE_EXECUTOR = Runnable::run;

    private static final int TEST_NETWORK_MTU = 1500;

    private static final int VCN_STATUS_CODE_AWAIT_TIMEOUT = -1;

    private static final InetAddress LOCAL_ADDRESS =
            InetAddresses.parseNumericAddress("198.51.100.1");
    private static final InetAddress SECONDARY_LOCAL_ADDRESS =
            InetAddresses.parseNumericAddress("198.51.100.2");

    private static final long IKE_DETERMINISTIC_INITIATOR_SPI =
            Long.parseLong("46B8ECA1E0D72A18", 16);

    private final Context mContext;
    private final VcnManager mVcnManager;
    private final SubscriptionManager mSubscriptionManager;
    private final TelephonyManager mTelephonyManager;
    private final ConnectivityManager mConnectivityManager;
    private final CarrierConfigManager mCarrierConfigManager;
    private final int mOldCaptivePortalMode;

    public VcnManagerTest() {
        mContext = InstrumentationRegistry.getContext();
        mVcnManager = mContext.getSystemService(VcnManager.class);
        mSubscriptionManager = mContext.getSystemService(SubscriptionManager.class);
        mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
        mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
        mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);

        mOldCaptivePortalMode = getCaptivePortalMode(mContext, CAPTIVE_PORTAL_MODE_PROMPT);
    }

    @Before
    public void setUp() throws Exception {
        final boolean hasFeatureTelephony =
                mContext.getPackageManager().hasSystemFeature(FEATURE_TELEPHONY);
        final boolean hasFeatureTelSubscription =
                mContext.getPackageManager().hasSystemFeature(FEATURE_TELEPHONY_SUBSCRIPTION);
        final boolean hasTelephonyFlag = hasFeatureTelephony || hasFeatureTelSubscription;

        // Before V, only devices with FEATURE_TELEPHONY are required to run the tests. Starting
        // from V, tests are also required on following cases:
        //
        // Device that has a non-null VcnManager even if it has neither of FEATURE_TELEPHONY or
        // FEATURE_TELEPHONY_SUBSCRIPTION.
        //
        // Device that has FEATURE_TELEPHONY_SUBSCRIPTION. This should not be a new requirement
        // since before V devices with FEATURE_TELEPHONY_SUBSCRIPTION are already enforced to have
        // FEATURE_TELEPHONY.
        assumeTrue(hasTelephonyFlag || mVcnManager != null);

        getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();

        // Ensure Internet probing check will be performed on VCN networks
        setCaptivePortalMode(mContext, CAPTIVE_PORTAL_MODE_PROMPT);

        runShellCommand("cmd connectivity airplane-mode disable");
    }

    @After
    public void tearDown() throws Exception {
        setCaptivePortalMode(mContext, mOldCaptivePortalMode);
        getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
    }

    private VcnConfig.Builder buildVcnConfigBase() {
        return buildVcnConfigBase(new ArrayList<VcnUnderlyingNetworkTemplate>());
    }

    private VcnConfig.Builder buildVcnConfigBase(List<VcnUnderlyingNetworkTemplate> nwTemplate) {
        // TODO(b/191371669): remove the exposed MMS capability and use
        // VcnGatewayConnectionConfigTest.buildVcnGatewayConnectionConfig() instead
        return new VcnConfig.Builder(mContext)
                .addGatewayConnectionConfig(
                        VcnGatewayConnectionConfigTest.buildVcnGatewayConnectionConfigBase()
                                .addExposedCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
                                .setVcnUnderlyingNetworkPriorities(nwTemplate)
                                .addGatewayOption(
                                        VCN_GATEWAY_OPTION_ENABLE_DATA_STALL_RECOVERY_WITH_MOBILITY)
                                .build());
    }

    private VcnConfig buildVcnConfig() {
        return buildVcnConfigBase().build();
    }

    private VcnConfig buildTestModeVcnConfig() {
        return buildVcnConfigBase().setIsTestModeProfile().build();
    }

    private int verifyAndGetValidDataSubId() throws Exception {
        // Wait for an active sub ID to mitigate the cuttlefish test issue where the CTS will
        // start before a valid data subId is ready. In most cases this should return immediately
        // without needing to wait.
        waitUntil(
                "There must be an active data subscription to complete CTS",
                ACTIVE_SUB_ID_TIMEOUT_SECONDS,
                () ->
                        SubscriptionManager.getDefaultDataSubscriptionId()
                                != INVALID_SUBSCRIPTION_ID);
        return SubscriptionManager.getDefaultDataSubscriptionId();
    }

    @Test(expected = SecurityException.class)
    public void testSetVcnConfig_noCarrierPrivileges() throws Exception {
        mVcnManager.setVcnConfig(new ParcelUuid(UUID.randomUUID()), buildVcnConfig());
    }

    @Test
    public void testSetVcnConfig_withCarrierPrivileges() throws Exception {
        final int dataSubId = verifyAndGetValidDataSubId();
        CarrierPrivilegeUtils.withCarrierPrivileges(mContext, dataSubId, () -> {
            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, dataSubId, (subGrp) -> {
                mVcnManager.setVcnConfig(subGrp, buildVcnConfig());
            });
        });

        assertFalse(mTelephonyManager.createForSubscriptionId(dataSubId).hasCarrierPrivileges());
    }

    @Test(expected = SecurityException.class)
    public void testClearVcnConfig_noCarrierPrivileges() throws Exception {
        mVcnManager.clearVcnConfig(new ParcelUuid(UUID.randomUUID()));
    }

    @Test
    public void testClearVcnConfig_withCarrierPrivileges() throws Exception {
        final int dataSubId = verifyAndGetValidDataSubId();

        CarrierPrivilegeUtils.withCarrierPrivileges(mContext, dataSubId, () -> {
            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, dataSubId, (subGrp) -> {
                mVcnManager.clearVcnConfig(subGrp);
            });
        });
    }

    /** Test implementation of VcnNetworkPolicyChangeListener for verification purposes. */
    private static class TestVcnNetworkPolicyChangeListener
            implements VcnManager.VcnNetworkPolicyChangeListener {
        private final CompletableFuture<Void> mFutureOnPolicyChanged = new CompletableFuture<>();

        @Override
        public void onPolicyChanged() {
            mFutureOnPolicyChanged.complete(null /* unused */);
        }

        public void awaitOnPolicyChanged() throws Exception {
            mFutureOnPolicyChanged.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
        }
    }

    @Test(expected = SecurityException.class)
    public void testAddVcnNetworkPolicyChangeListener_noNetworkFactoryPermission()
            throws Exception {
        // Drop shell permission identity to test unpermissioned behavior.
        getInstrumentation().getUiAutomation().dropShellPermissionIdentity();

        final TestVcnNetworkPolicyChangeListener listener =
                new TestVcnNetworkPolicyChangeListener();

        try {
            mVcnManager.addVcnNetworkPolicyChangeListener(INLINE_EXECUTOR, listener);
        } finally {
            mVcnManager.removeVcnNetworkPolicyChangeListener(listener);
        }
    }

    @Test
    public void testRemoveVcnNetworkPolicyChangeListener_noNetworkFactoryPermission() {
        final TestVcnNetworkPolicyChangeListener listener =
                new TestVcnNetworkPolicyChangeListener();

        mVcnManager.removeVcnNetworkPolicyChangeListener(listener);
    }

    @Test(expected = SecurityException.class)
    public void testApplyVcnNetworkPolicy_noNetworkFactoryPermission() throws Exception {
        // Drop shell permission identity to test unpermissioned behavior.
        getInstrumentation().getUiAutomation().dropShellPermissionIdentity();

        final NetworkCapabilities nc = new NetworkCapabilities.Builder().build();
        final LinkProperties lp = new LinkProperties();

        mVcnManager.applyVcnNetworkPolicy(nc, lp);
    }

    @Test
    public void testApplyVcnNetworkPolicy_manageTestNetworkRequiresTransportTest()
            throws Exception {
        final NetworkCapabilities nc =
                new NetworkCapabilities.Builder().addTransportType(TRANSPORT_CELLULAR).build();
        final LinkProperties lp = new LinkProperties();

        runWithShellPermissionIdentity(
                () -> {
                    try {
                        mVcnManager.applyVcnNetworkPolicy(nc, lp);
                        fail("Expected IllegalStateException for applyVcnNetworkPolicy");
                    } catch (IllegalStateException e) {
                    }
                },
                android.Manifest.permission.MANAGE_TEST_NETWORKS);
    }

    private TestNetworkWrapper createTestNetworkWrapperForPolicyTest(
            boolean isRestricted, int subId) throws Exception {
        final Set<Integer> capabilities = new HashSet<>();
        capabilities.add(NET_CAPABILITY_CBS);
        if (!isRestricted) {
            capabilities.add(NET_CAPABILITY_NOT_RESTRICTED);
        }

        return createTestNetworkWrapper(subId, LOCAL_ADDRESS, capabilities);
    }

    private VcnConfig buildVcnConfigWithTransportTestRestricted() {
        return buildVcnConfigBase()
                .setIsTestModeProfile()
                .setRestrictedUnderlyingNetworkTransports(Set.of(TRANSPORT_TEST))
                .build();
    }

    @Test
    public void testApplyVcnNetworkPolicyDuringVcnSetup_onUnrestrictedNetwork() throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        final VcnConfig vcnConfig = buildVcnConfigWithTransportTestRestricted();

        try (TestNetworkWrapper networkWrapperUnrestricted =
                createTestNetworkWrapperForPolicyTest(false /* isRestricted */, subId)) {
            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        cellNetworkCb.waitForAvailable();

                        // Attempt VCN setup on an unrestricted network; expect the network to
                        // change to be restricted
                        mVcnManager.setVcnConfig(subGrp, vcnConfig);

                        VcnNetworkPolicyResult policyResult =
                                networkWrapperUnrestricted.awaitVcnNetworkPolicyChange();

                        // Expect teardown due to restriction capability change
                        assertTrue(policyResult.isTeardownRequested());
                        assertFalse(
                                policyResult
                                        .getNetworkCapabilities()
                                        .hasCapability(NET_CAPABILITY_NOT_RESTRICTED));

                        // Verify underlying network is lost
                        networkWrapperUnrestricted.vcnNetworkCallback.waitForLost();

                        mVcnManager.clearVcnConfig(subGrp);
                    });
        }
    }

    @Test
    public void testApplyVcnNetworkPolicyDuringVcnSetup_onRestrictedNetwork() throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        final VcnConfig vcnConfig = buildVcnConfigWithTransportTestRestricted();

        try (TestNetworkWrapper networkWrapperRestricted =
                createTestNetworkWrapperForPolicyTest(true /* isRestricted */, subId)) {

            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        // Set up VCN on a restricted network
                        final VcnSetupResult vcnSetupResult =
                                setupAndGetVcnNetwork(
                                        subGrp,
                                        cellNetwork,
                                        cellNetworkCb,
                                        vcnConfig,
                                        networkWrapperRestricted);

                        VcnNetworkPolicyResult policyResult =
                                networkWrapperRestricted.awaitVcnNetworkPolicyChange();

                        // Do not expect teardown since the restriction capability does not change
                        assertFalse(policyResult.isTeardownRequested());
                        assertFalse(
                                policyResult
                                        .getNetworkCapabilities()
                                        .hasCapability(NET_CAPABILITY_NOT_RESTRICTED));

                        clearVcnConfigsAndVerifyNetworkTeardown(
                                subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                    });
        }
    }

    private void waitForSafeMode(TestNetworkWrapper networkWrapper) throws Exception {
        // Once VCN starts, the test network should lose NOT_VCN_MANAGED
        waitForExpectedUnderlyingNetworkWithCapabilities(
                networkWrapper,
                false /* expectNotVcnManaged */,
                false /* expectNotMetered */,
                TestNetworkWrapper.NETWORK_CB_TIMEOUT_MS);

        // After VCN has started up, wait for safemode to kick in and expect the
        // underlying Test Network to regain NOT_VCN_MANAGED.
        waitForExpectedUnderlyingNetworkWithCapabilities(
                networkWrapper,
                true /* expectNotVcnManaged */,
                false /* expectNotMetered */,
                SAFEMODE_TIMEOUT_MILLIS);
    }

    private void verifyApplyVcnNetworkPolicyPostVcnSetupChangeNetworkRestriction(
            boolean isSafeMode, boolean isRestrictedBefore, boolean expectRestrictedAfter)
            throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        final VcnConfig vcnConfig = buildVcnConfigWithTransportTestRestricted();

        try (TestNetworkWrapper networkWrapperRestricted =
                createTestNetworkWrapperForPolicyTest(true /* isRestricted */, subId)) {

            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        // Set up VCN on a restricted network
                        final VcnSetupResult vcnSetupResult =
                                setupAndGetVcnNetwork(
                                        subGrp,
                                        cellNetwork,
                                        cellNetworkCb,
                                        vcnConfig,
                                        networkWrapperRestricted);

                        if (isSafeMode) {
                            waitForSafeMode(networkWrapperRestricted);
                        }

                        // Bring up another test network and verify its restriction capability
                        // change.
                        try (TestNetworkWrapper testNetworkWrapper =
                                createTestNetworkWrapperForPolicyTest(isRestrictedBefore, subId)) {

                            // The requested NetworkCapabilities should have been changed by
                            // VcnManager before the test network was brought up. Verify it by
                            // checking the NetworkCapabilities after the network setup.
                            final NetworkCapabilities nc =
                                    mConnectivityManager.getNetworkCapabilities(
                                            testNetworkWrapper.tunNetwork);
                            assertEquals(
                                    !expectRestrictedAfter,
                                    nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
                        }

                        clearVcnConfigsAndVerifyNetworkTeardown(
                                subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                    });
        }
    }

    @Test
    public void testApplyVcnNetworkPolicy_activeMode_onRestrictedNetwork() throws Exception {
        verifyApplyVcnNetworkPolicyPostVcnSetupChangeNetworkRestriction(
                false /* isSafeMode */,
                true /* isRestrictedBefore */,
                true /* expectRestrictedAfter */);
    }

    @Test
    public void testApplyVcnNetworkPolicy_safeMode_onRestrictedNetwork() throws Exception {
        verifyApplyVcnNetworkPolicyPostVcnSetupChangeNetworkRestriction(
                true /* isSafeMode */,
                true /* isRestrictedBefore */,
                true /* expectRestrictedAfter */);
    }

    @Test
    public void testApplyVcnNetworkPolicy_activeMode_onUnrestrictedNetwork() throws Exception {
        verifyApplyVcnNetworkPolicyPostVcnSetupChangeNetworkRestriction(
                false /* isSafeMode */,
                false /* isRestrictedBefore */,
                true /* expectRestrictedAfter */);
    }

    @Test
    public void testApplyVcnNetworkPolicy_safeMode_onUnrestrictedNetwork() throws Exception {
        verifyApplyVcnNetworkPolicyPostVcnSetupChangeNetworkRestriction(
                true /* isSafeMode */,
                false /* isRestrictedBefore */,
                false /* expectRestrictedAfter */);
    }

    /** Test implementation of VcnStatusCallback for verification purposes. */
    private static class TestVcnStatusCallback extends VcnManager.VcnStatusCallback {
        private final BlockingQueue<Integer> mOnStatusChangedHistory = new LinkedBlockingQueue<>();
        private final BlockingQueue<GatewayConnectionError> mOnGatewayConnectionErrorHistory =
                new LinkedBlockingQueue<>();

        @Override
        public void onStatusChanged(int statusCode) {
            mOnStatusChangedHistory.offer(statusCode);
        }

        @Override
        public void onGatewayConnectionError(
                @NonNull String gatewayConnectionName, int errorCode, @Nullable Throwable detail) {
            mOnGatewayConnectionErrorHistory.offer(
                    new GatewayConnectionError(gatewayConnectionName, errorCode, detail));
        }

        public int awaitOnStatusChanged() throws Exception {
            final Integer status = mOnStatusChangedHistory.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS);

            // Null means timeout
            return status == null ? VCN_STATUS_CODE_AWAIT_TIMEOUT : status;
        }

        public GatewayConnectionError awaitOnGatewayConnectionError() throws Exception {
            return mOnGatewayConnectionErrorHistory.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS);
        }
    }

    private void verifyVcnStatus(ParcelUuid subGrp, int expectedStatus) throws Exception {
        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
        mVcnManager.registerVcnStatusCallback(subGrp, INLINE_EXECUTOR, callback);

        assertEquals(expectedStatus, callback.awaitOnStatusChanged());

        mVcnManager.unregisterVcnStatusCallback(callback);
    }

    /** Info class for organizing VcnStatusCallback#onGatewayConnectionError response data. */
    private static class GatewayConnectionError {
        @NonNull public final String gatewayConnectionName;
        public final int errorCode;
        @Nullable public final Throwable detail;

        public GatewayConnectionError(
                @NonNull String gatewayConnectionName, int errorCode, @Nullable Throwable detail) {
            this.gatewayConnectionName = gatewayConnectionName;
            this.errorCode = errorCode;
            this.detail = detail;
        }
    }

    private void registerVcnStatusCallbackForSubId(
            @NonNull TestVcnStatusCallback callback, int subId) throws Exception {
        CarrierPrivilegeUtils.withCarrierPrivileges(mContext, subId, () -> {
            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, subId, (subGrp) -> {
                mVcnManager.registerVcnStatusCallback(subGrp, INLINE_EXECUTOR, callback);
            });
        });
    }

    @Test
    public void testRegisterVcnStatusCallback() throws Exception {
        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
        final int subId = verifyAndGetValidDataSubId();

        try {
            registerVcnStatusCallbackForSubId(callback, subId);

            final int statusCode = callback.awaitOnStatusChanged();
            assertEquals(VcnManager.VCN_STATUS_CODE_NOT_CONFIGURED, statusCode);
        } finally {
            mVcnManager.unregisterVcnStatusCallback(callback);
        }
    }

    @Test
    public void testRegisterVcnStatusCallback_reuseUnregisteredCallback() throws Exception {
        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
        final int subId = verifyAndGetValidDataSubId();

        try {
            registerVcnStatusCallbackForSubId(callback, subId);
            mVcnManager.unregisterVcnStatusCallback(callback);
            registerVcnStatusCallbackForSubId(callback, subId);
        } finally {
            mVcnManager.unregisterVcnStatusCallback(callback);
        }
    }

    @Test(expected = IllegalStateException.class)
    public void testRegisterVcnStatusCallback_duplicateRegister() throws Exception {
        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
        final int subId = verifyAndGetValidDataSubId();

        try {
            registerVcnStatusCallbackForSubId(callback, subId);
            registerVcnStatusCallbackForSubId(callback, subId);
        } finally {
            mVcnManager.unregisterVcnStatusCallback(callback);
        }
    }

    @Test
    public void testUnregisterVcnStatusCallback() throws Exception {
        final TestVcnStatusCallback callback = new TestVcnStatusCallback();

        mVcnManager.unregisterVcnStatusCallback(callback);
    }

    private TestNetworkWrapper createTestNetworkWrapper(
            int subId, InetAddress localAddress, Set<Integer> capabilities) throws Exception {
        TestNetworkWrapper testNetworkWrapper =
                new TestNetworkWrapper(
                        mContext,
                        TEST_NETWORK_MTU,
                        capabilities,
                        Collections.singleton(subId),
                        localAddress);
        assertNotNull("No test network found", testNetworkWrapper.tunNetwork);
        return testNetworkWrapper;
    }

    private TestNetworkWrapper createTestNetworkWrapper(
            boolean isMetered, int subId, InetAddress localAddress) throws Exception {
        final Set<Integer> capabilities = new HashSet<>();
        capabilities.add(NET_CAPABILITY_CBS);
        if (!isMetered) {
            capabilities.add(NET_CAPABILITY_NOT_METERED);
        }

        return createTestNetworkWrapper(subId, localAddress, capabilities);
    }

    @Test
    public void testVcnManagedNetworkLosesNotVcnManagedCapability() throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
            // Before the VCN starts, the test network should have NOT_VCN_MANAGED
            waitForExpectedUnderlyingNetworkWithCapabilities(
                    testNetworkWrapper,
                    true /* expectNotVcnManaged */,
                    false /* expectNotMetered */,
                    TestNetworkWrapper.NETWORK_CB_TIMEOUT_MS);

            CarrierPrivilegeUtils.withCarrierPrivilegesForShell(mContext, subId, () -> {
                SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, subId, (subGrp) -> {
                    mVcnManager.setVcnConfig(subGrp, buildVcnConfig());

                    // Once VCN starts, the test network should lose NOT_VCN_MANAGED
                    waitForExpectedUnderlyingNetworkWithCapabilities(
                            testNetworkWrapper,
                            false /* expectNotVcnManaged */,
                            false /* expectNotMetered */,
                            TestNetworkWrapper.NETWORK_CB_TIMEOUT_MS);

                    mVcnManager.clearVcnConfig(subGrp);

                    // After the VCN tears down, the test network should have
                    // NOT_VCN_MANAGED again
                    waitForExpectedUnderlyingNetworkWithCapabilities(
                            testNetworkWrapper,
                            true /* expectNotVcnManaged */,
                            false /* expectNotMetered */,
                            TestNetworkWrapper.NETWORK_CB_TIMEOUT_MS);
                });
            });
        }
    }

    private void waitForExpectedUnderlyingNetworkWithCapabilities(
            TestNetworkWrapper testNetworkWrapper,
            boolean expectNotVcnManaged,
            boolean expectNotMetered,
            long timeoutMillis)
            throws Exception {
        final long start = SystemClock.elapsedRealtime();

        // Wait for NetworkCapabilities changes until they match the expected capabilities
        do {
            final CapabilitiesChangedEvent capabilitiesChangedEvent =
                    testNetworkWrapper.vcnNetworkCallback.waitForOnCapabilitiesChanged(
                            timeoutMillis);
            assertNotNull("Failed to receive NetworkCapabilities change", capabilitiesChangedEvent);

            final NetworkCapabilities nc = capabilitiesChangedEvent.networkCapabilities;
            if (testNetworkWrapper.tunNetwork.equals(capabilitiesChangedEvent.network)
                    && nc.hasCapability(NET_CAPABILITY_VALIDATED)
                    && expectNotVcnManaged == nc.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
                    && expectNotMetered == nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
                return;
            }
        } while (SystemClock.elapsedRealtime() - start < timeoutMillis);

        fail(
                "Expected update for network="
                        + testNetworkWrapper.tunNetwork.getNetId()
                        + ". Wanted NOT_VCN_MANAGED="
                        + expectNotVcnManaged
                        + " NOT_METERED="
                        + expectNotMetered);
    }

    private interface VcnTestRunnable {
        void runTest(ParcelUuid subGrp, Network cellNetwork, VcnTestNetworkCallback cellNetworkCb)
                throws Exception;
    }

    private void verifyUnderlyingCellAndRunTest(int subId, VcnTestRunnable test) throws Exception {
        // Get current cell Network then wait for it to drop (due to losing NOT_VCN_MANAGED)
        // before waiting for VCN Network.
        final NetworkRequest cellNetworkReq =
                new NetworkRequest.Builder()
                        .addTransportType(TRANSPORT_CELLULAR)
                        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                        .build();
        final VcnTestNetworkCallback cellNetworkCb = new VcnTestNetworkCallback();
        mConnectivityManager.requestNetwork(cellNetworkReq, cellNetworkCb);
        final Network cellNetwork = cellNetworkCb.waitForAvailable();
        assertNotNull("No cell network found", cellNetwork);

        CarrierPrivilegeUtils.withCarrierPrivilegesForShell(mContext, subId, () -> {
            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(
                mContext,
                subId,
                (subGrp) -> {
                    test.runTest(subGrp, cellNetwork, cellNetworkCb);
                }
            );
        });
        mConnectivityManager.unregisterNetworkCallback(cellNetworkCb);
    }

    @Test
    public void testSetVcnConfigOnTestNetwork() throws Exception {
        final int subId = verifyAndGetValidDataSubId();

        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
            verifyUnderlyingCellAndRunTest(subId, (subGrp, cellNetwork, cellNetworkCb) -> {
                final VcnSetupResult vcnSetupResult =
                    setupAndGetVcnNetwork(subGrp, cellNetwork, cellNetworkCb, testNetworkWrapper);

                clearVcnConfigsAndVerifyNetworkTeardown(
                        subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
            });
        }
    }

    @Test
    public void testSetVcnConfigOnTestNetworkAndHandleDataStall() throws Exception {
        final int subId = verifyAndGetValidDataSubId();

        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        final VcnSetupResult vcnSetupResult =
                                setupAndGetVcnNetwork(
                                        subGrp, cellNetwork, cellNetworkCb, testNetworkWrapper);

                        mConnectivityManager.simulateDataStall(
                                DETECTION_METHOD_DNS_EVENTS,
                                System.currentTimeMillis(),
                                vcnSetupResult.vcnNetwork,
                                new PersistableBundle() /* extra data stall info; unused */);

                        injectAndVerifyIkeMobikePackets(testNetworkWrapper.ikeTunUtils);

                        clearVcnConfigsAndVerifyNetworkTeardown(
                                subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                    });
        }
    }

    private TestNetworkWrapper createTestNetworkForNetworkSelection(
            int subId, Set<Integer> capabilities) throws Exception {
        return createTestNetworkWrapper(subId, LOCAL_ADDRESS, capabilities);
    }

    private void verifyVcnMigratesToPreferredUnderlyingNetwork(
            VcnConfig vcnConfig, Set<Integer> capSetLessPreferred, Set<Integer> capSetPreferred)
            throws Exception {
        final int subId = verifyAndGetValidDataSubId();

        // Start on a less preferred network.
        try (TestNetworkWrapper testNetworkWrapperLessPreferred =
                createTestNetworkForNetworkSelection(subId, capSetLessPreferred)) {
            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        final VcnSetupResult vcnSetupResult =
                                setupAndGetVcnNetwork(
                                        subGrp,
                                        cellNetwork,
                                        cellNetworkCb,
                                        vcnConfig,
                                        testNetworkWrapperLessPreferred);

                        // Then bring up a more preferred network, and expect to switch to it.
                        try (TestNetworkWrapper testNetworkWrapperPreferred =
                                createTestNetworkForNetworkSelection(subId, capSetPreferred)) {
                            injectAndVerifyIkeMobikePackets(
                                    testNetworkWrapperPreferred.ikeTunUtils);

                            clearVcnConfigsAndVerifyNetworkTeardown(
                                    subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                        }
                    });
        }
    }

    private void verifyVcnDoesNotSelectLessPreferredUnderlyingNetwork(
            VcnConfig vcnConfig, Set<Integer> capSetLessPreferred, Set<Integer> capSetPreferred)
            throws Exception {
        final int subId = verifyAndGetValidDataSubId();

        // Start on a more preferred network.
        try (TestNetworkWrapper testNetworkWrapperPreferred =
                createTestNetworkForNetworkSelection(subId, capSetPreferred)) {
            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        final VcnSetupResult vcnSetupResult =
                                setupAndGetVcnNetwork(
                                        subGrp,
                                        cellNetwork,
                                        cellNetworkCb,
                                        vcnConfig,
                                        testNetworkWrapperPreferred);

                        // Then bring up a less preferred network, and expect the VCN underlying
                        // network does not change.
                        try (TestNetworkWrapper testNetworkWrapperLessPreferred =
                                createTestNetworkForNetworkSelection(subId, capSetLessPreferred)) {
                            injectAndVerifyIkeDpdPackets(
                                    testNetworkWrapperPreferred.ikeTunUtils,
                                    vcnSetupResult.ikeExchangePortPair);

                            clearVcnConfigsAndVerifyNetworkTeardown(
                                    subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                        }
                    });
        }
    }

    private void verifyVcnMigratesAfterPreferredUnderlyingNetworkDies(
            VcnConfig vcnConfig, Set<Integer> capSetLessPreferred, Set<Integer> capSetPreferred)
            throws Exception {
        final int subId = verifyAndGetValidDataSubId();

        // Start on a more preferred network
        try (TestNetworkWrapper testNetworkWrapperPreferred =
                createTestNetworkForNetworkSelection(subId, capSetPreferred)) {
            verifyUnderlyingCellAndRunTest(
                    subId,
                    (subGrp, cellNetwork, cellNetworkCb) -> {
                        final VcnSetupResult vcnSetupResult =
                                setupAndGetVcnNetwork(
                                        subGrp,
                                        cellNetwork,
                                        cellNetworkCb,
                                        vcnConfig,
                                        testNetworkWrapperPreferred);

                        // Bring up a less preferred network
                        try (TestNetworkWrapper testNetworkWrapperLessPreferred =
                                createTestNetworkForNetworkSelection(subId, capSetLessPreferred)) {
                            // Teardown the preferred network
                            testNetworkWrapperPreferred.close();
                            testNetworkWrapperPreferred.vcnNetworkCallback.waitForLost();

                            // Verify the VCN switches to the remaining less preferred network
                            injectAndVerifyIkeMobikePackets(
                                    testNetworkWrapperLessPreferred.ikeTunUtils);

                            clearVcnConfigsAndVerifyNetworkTeardown(
                                    subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                        }
                    });
        }
    }

    private VcnCellUnderlyingNetworkTemplate.Builder createCellTemplateBaseBuilder()
            throws Exception {
        return new VcnCellUnderlyingNetworkTemplate.Builder().setInternet(MATCH_ANY);
    }

    private VcnConfig createVcnConfigPrefersMetered() throws Exception {
        final List<VcnUnderlyingNetworkTemplate> nwTemplates = new ArrayList<>();
        nwTemplates.add(
                createCellTemplateBaseBuilder()
                        .setCbs(MATCH_REQUIRED)
                        .setMetered(MATCH_REQUIRED)
                        .build());
        nwTemplates.add(
                createCellTemplateBaseBuilder()
                        .setCbs(MATCH_REQUIRED)
                        .setMetered(MATCH_FORBIDDEN)
                        .build());
        return buildVcnConfigBase(nwTemplates).setIsTestModeProfile().build();
    }

    @Test
    public void testVcnMigratesToPreferredUnderlyingNetwork_preferMetered() throws Exception {
        verifyVcnMigratesToPreferredUnderlyingNetwork(
                createVcnConfigPrefersMetered(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_CBS),
                Set.of(NET_CAPABILITY_CBS));
    }

    @Test
    public void testVcnDoesNotSelectLessPreferredUnderlyingNetwork_preferMetered()
            throws Exception {
        verifyVcnDoesNotSelectLessPreferredUnderlyingNetwork(
                createVcnConfigPrefersMetered(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_CBS),
                Set.of(NET_CAPABILITY_CBS));
    }

    @Test
    public void testVcnMigratesAfterPreferredUnderlyingNetworkDies_preferMetered()
            throws Exception {
        verifyVcnMigratesAfterPreferredUnderlyingNetworkDies(
                createVcnConfigPrefersMetered(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_CBS),
                Set.of(NET_CAPABILITY_CBS));
    }

    private VcnConfig createVcnConfigPrefersCbs() throws Exception {
        final List<VcnUnderlyingNetworkTemplate> nwTemplates = new ArrayList<>();
        nwTemplates.add(createCellTemplateBaseBuilder().setCbs(MATCH_REQUIRED).build());
        nwTemplates.add(createCellTemplateBaseBuilder().setRcs(MATCH_REQUIRED).build());

        return buildVcnConfigBase(nwTemplates).setIsTestModeProfile().build();
    }

    @Test
    public void testVcnMigratesToPreferredUnderlyingNetwork_preferCbs() throws Exception {
        verifyVcnMigratesToPreferredUnderlyingNetwork(
                createVcnConfigPrefersCbs(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_CBS));
    }

    @Test
    public void testVcnDoesNotSelectLessPreferredUnderlyingNetwork_preferCbs() throws Exception {
        verifyVcnDoesNotSelectLessPreferredUnderlyingNetwork(
                createVcnConfigPrefersCbs(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_CBS));
    }

    @Test
    public void testVcnMigratesAfterPreferredUnderlyingNetworkDies_preferCbs() throws Exception {
        verifyVcnMigratesAfterPreferredUnderlyingNetworkDies(
                createVcnConfigPrefersCbs(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_CBS));
    }

    private VcnConfig createVcnConfigPrefersNonCbs() throws Exception {
        final List<VcnUnderlyingNetworkTemplate> nwTemplates = new ArrayList<>();
        nwTemplates.add(
                createCellTemplateBaseBuilder()
                        .setRcs(MATCH_REQUIRED)
                        .setCbs(MATCH_FORBIDDEN)
                        .build());
        nwTemplates.add(
                createCellTemplateBaseBuilder().setRcs(MATCH_REQUIRED).setCbs(MATCH_ANY).build());

        return buildVcnConfigBase(nwTemplates).setIsTestModeProfile().build();
    }

    @Test
    public void testVcnMigratesToPreferredUnderlyingNetwork_preferNonCbs() throws Exception {
        verifyVcnMigratesToPreferredUnderlyingNetwork(
                createVcnConfigPrefersNonCbs(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS, NET_CAPABILITY_CBS),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS));
    }

    @Test
    public void testVcnDoesNotSelectLessPreferredUnderlyingNetwork_preferNonCbs() throws Exception {
        verifyVcnDoesNotSelectLessPreferredUnderlyingNetwork(
                createVcnConfigPrefersNonCbs(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS, NET_CAPABILITY_CBS),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS));
    }

    @Test
    public void testVcnMigratesAfterPreferredUnderlyingNetworkDies_preferNonCbs() throws Exception {
        verifyVcnMigratesAfterPreferredUnderlyingNetworkDies(
                createVcnConfigPrefersNonCbs(),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS, NET_CAPABILITY_CBS),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS));
    }

    @Test
    public void testSetVcnWithCbsMatchAny_preferCbsNetworkOverUnmatchedNetwork() throws Exception {
        final List<VcnUnderlyingNetworkTemplate> nwTemplates = new ArrayList<>();
        nwTemplates.add(
                createCellTemplateBaseBuilder().setRcs(MATCH_REQUIRED).setCbs(MATCH_ANY).build());

        final VcnConfig vcnConfig = buildVcnConfigBase(nwTemplates).setIsTestModeProfile().build();

        verifyVcnMigratesToPreferredUnderlyingNetwork(
                vcnConfig,
                Set.of(NET_CAPABILITY_NOT_METERED),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS, NET_CAPABILITY_CBS));
    }

    @Test
    public void testSetVcnWithCbsMatchAny_preferNonCbsNetworkOverUnmatchedNetwork()
            throws Exception {
        final List<VcnUnderlyingNetworkTemplate> nwTemplates = new ArrayList<>();
        nwTemplates.add(
                createCellTemplateBaseBuilder().setRcs(MATCH_REQUIRED).setCbs(MATCH_ANY).build());

        final VcnConfig vcnConfig = buildVcnConfigBase(nwTemplates).setIsTestModeProfile().build();

        verifyVcnMigratesToPreferredUnderlyingNetwork(
                vcnConfig,
                Set.of(NET_CAPABILITY_NOT_METERED),
                Set.of(NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_RCS));
    }

    @Test
    public void testVcnNoUnderlyingNetworkSelectedFallback() throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        final List<VcnUnderlyingNetworkTemplate> nwTemplates = new ArrayList<>();
        nwTemplates.add(
                new VcnWifiUnderlyingNetworkTemplate.Builder().setMetered(MATCH_REQUIRED).build());
        final VcnConfig vcnConfig = buildVcnConfigBase(nwTemplates).setIsTestModeProfile().build();

        // Bring up a network that does not match any of the configured network templates
        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(false /* isMetered */, subId, LOCAL_ADDRESS)) {
            verifyUnderlyingCellAndRunTest(subId, (subGrp, cellNetwork, cellNetworkCb) -> {
                // Verify the VCN can still be set up on the only one underlying network
                final VcnSetupResult vcnSetupResult =
                        setupAndGetVcnNetwork(
                                subGrp,
                                cellNetwork,
                                cellNetworkCb,
                                vcnConfig,
                                testNetworkWrapper);

                clearVcnConfigsAndVerifyNetworkTeardown(
                        subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
            });
        }
    }

    private static class VcnSetupResult {
        public final Network vcnNetwork;
        public final PortPair ikeExchangePortPair;

        VcnSetupResult(Network vcnNetwork, PortPair ikeExchangePortPair) {
            this.vcnNetwork = vcnNetwork;
            this.ikeExchangePortPair = ikeExchangePortPair;
        }
    }

    private VcnSetupResult setupAndGetVcnNetwork(
            @NonNull ParcelUuid subGrp,
            @NonNull Network cellNetwork,
            @NonNull VcnTestNetworkCallback cellNetworkCb,
            @NonNull VcnConfig testModeVcnConfig,
            @NonNull TestNetworkWrapper testNetworkWrapper)
            throws Exception {
        cellNetworkCb.waitForAvailable();
        mVcnManager.setVcnConfig(subGrp, testModeVcnConfig);

        // Wait until the cell Network is lost (due to losing NOT_VCN_MANAGED) to wait for
        // VCN network
        final Network lostCellNetwork = cellNetworkCb.waitForLost();
        assertEquals(cellNetwork, lostCellNetwork);

        final PortPair ikeExchangePortPair =
                injectAndVerifyIkeSessionNegotiationPackets(testNetworkWrapper.ikeTunUtils);

        final Network vcnNetwork = cellNetworkCb.waitForAvailable();
        assertNotNull("VCN network did not come up", vcnNetwork);
        return new VcnSetupResult(vcnNetwork, ikeExchangePortPair);
    }

    private VcnSetupResult setupAndGetVcnNetwork(
            @NonNull ParcelUuid subGrp,
            @NonNull Network cellNetwork,
            @NonNull VcnTestNetworkCallback cellNetworkCb,
            @NonNull TestNetworkWrapper testNetworkWrapper)
            throws Exception {
        return setupAndGetVcnNetwork(
                subGrp, cellNetwork, cellNetworkCb, buildTestModeVcnConfig(), testNetworkWrapper);
    }

    private PortPair injectAndVerifyIkeSessionNegotiationPackets(@NonNull IkeTunUtils ikeTunUtils)
            throws Exception {
        // Generated by forcing IKE to use Test Mode (RandomnessFactory#mIsTestModeEnabled) and
        // capturing IKE packets with a live server.
        final String ikeInitResp =
                "46b8eca1e0d72a189b9f8e0158e1c0a52120222000000000000001d022000030"
                        + "0000002c010100040300000c0100000c800e0080030000080300000803000008"
                        + "02000008000000080400000e28000108000e0000164d3413d855a1642d4d6355"
                        + "a8ef6666bfaa28a4b5264600c9ffbaef7930bd33af49022926013aae0a48d764"
                        + "750ccb3987605957e31a2ef0e6838cfa67af989933c2879434081c4e9787f0d4"
                        + "4da0d7dacca5589702a4537ee4fb18e8db21a948b245260f55212a1c619f61c6"
                        + "fa1caaff4474082f9714b14ef4bcc7b2b8f43fcb939931119e53b05274faec65"
                        + "2816c563529e60c1a88183eba9c456ecb644faf57b726b83e3242e08489d95e9"
                        + "81e59c7ad82cf3cdfb00fe0213c4e65d61e88bbefbd536261027da722a2bbf89"
                        + "c6378e63ce6fbcef282421e5576bba1b2faa3c4c2d41028f91df7ba165a24a18"
                        + "fcba4f96db3e5e0eed76dc7c3c432362dd4a82d32900002461cbd03c08819730"
                        + "f1060ed0c0446f784eb8dd884d3f73f54eb2b0c3071cc4f32900001c00004004"
                        + "07150f3fd9584dbebb7e88ad256c7bfb9b0bb55a2900001c00004005e3aa3788"
                        + "7040e38dbb4de8fd435161cce904ec59290000080000402e290000100000402f"
                        + "00020003000400050000000800004014";
        final String ikeAuthResp =
                "46b8eca1e0d72a189b9f8e0158e1c0a52e20232000000001000000fc240000e0"
                        + "1a666eb2a02b37682436a18fff5e9cef67b9096d6c7887ed235f8b5173c9469e"
                        + "361621b66849de2dbcabf956b3d055cafafd503530543540e81dac9bf8fb8826"
                        + "e08bc99e9ed2185d8f1322c8885abe4f98a9832c694da775eaa4ae69f17b8cbf"
                        + "b009bf82b4bf4012bca489595631c3168cd417f813e7d177d2ceb70766a0773c"
                        + "8819d8763627ddc9455ae3d5a5a03224020a66c8e58c8073c4a1fcf5d67cfa95"
                        + "15de86b392a63ff54ff5572302b9ce7725085b05839252794c3680f5d8f34019"
                        + "fa1930ea045d2a9987850e2049235c7328ef148370b6a3403408b987";

        ikeTunUtils.awaitReqAndInjectResp(
                IKE_DETERMINISTIC_INITIATOR_SPI,
                0 /* expectedMsgId */,
                false /* expectedUseEncap */,
                ikeInitResp);

        byte[] ikeAuthReqPkt =
                ikeTunUtils.awaitReqAndInjectResp(
                        IKE_DETERMINISTIC_INITIATOR_SPI,
                        1 /* expectedMsgId */,
                        true /* expectedUseEncap */,
                        ikeAuthResp);

        return IkeTunUtils.getSrcDestPortPair(ikeAuthReqPkt);
    }

    private void clearVcnConfigsAndVerifyNetworkTeardown(
            @NonNull ParcelUuid subGrp,
            @NonNull VcnTestNetworkCallback cellNetworkCb,
            @NonNull Network vcnNetwork)
            throws Exception {
        // Clear the history to remove other networks have been matched to the request
        cellNetworkCb.clearLostHistory();

        mVcnManager.clearVcnConfig(subGrp);

        // Expect VCN Network to disappear after VcnConfig is cleared.
        if (mConnectivityManager.getNetworkCapabilities(vcnNetwork) != null) {

            // If not already torn down, wait for teardown. In the event that the underlying network
            // has already regained the NOT_VCN_MANAGED bit (before the VCN's NetworkAgent teardown)
            // the VCN network MAY be immediately replaced with the underlying Cell, which only
            // fires an onAvailable for the new network, as opposed to an onLost() for the VCN
            // network. In that case, check that the VCN network has been unregistered.
            //
            // An alternative approach is to monitor #onAvailable as an indicator of potential
            // network loss. However, since #onAvailable can mean either 1) the new network has
            // higher priority, or 2) the old network is disconnected, this approach will introduce
            // a lot more complexities.
            final Network lostVcnNetwork = cellNetworkCb.waitForLost();
            if (lostVcnNetwork != null) {
                assertEquals(vcnNetwork, lostVcnNetwork);
            } else {
                assertNull(mConnectivityManager.getNetworkCapabilities(vcnNetwork));
            }
        } // Else already torn down, pass.
    }

    @Test
    public void testVcnMigrationAfterNetworkDies() throws Exception {
        final int subId = verifyAndGetValidDataSubId();

        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
            verifyUnderlyingCellAndRunTest(subId, (subGrp, cellNetwork, cellNetworkCb) -> {
                final VcnSetupResult vcnSetupResult =
                    setupAndGetVcnNetwork(subGrp, cellNetwork, cellNetworkCb, testNetworkWrapper);

                testNetworkWrapper.close();
                testNetworkWrapper.vcnNetworkCallback.waitForLost();

            try (TestNetworkWrapper secondaryTestNetworkWrapper =
                    createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
                try {
                    injectAndVerifyIkeMobikePackets(secondaryTestNetworkWrapper.ikeTunUtils);

                    clearVcnConfigsAndVerifyNetworkTeardown(
                            subGrp, cellNetworkCb, vcnSetupResult.vcnNetwork);
                } finally {
                    secondaryTestNetworkWrapper.close();
                }
            }
            });
        }
    }

    private void injectAndVerifyIkeMobikePackets(@NonNull IkeTunUtils ikeTunUtils)
            throws Exception {
        // Generated by forcing IKE to use Test Mode (RandomnessFactory#mIsTestModeEnabled) and
        // capturing IKE packets with a live server. To force the mobility event, use
        // IkeSession#setNetwork with the new desired Network.
        final String ikeUpdateSaResp =
                "46b8eca1e0d72a189b9f8e0158e1c0a52e202520000000020000007c29000060"
                        + "a1fd35f112d92d1df19ce734f6edf56ccda1bfd44ef6de428a097e04d5b40b28"
                        + "3897e42f23dd53e444dc6c676cf9a7d9d73bb3975d663ec351fb5ae4e56a55d8"
                        + "cbcf376a3b99cc6fd858621cc78b3017d895e4309f09a444028dba85";
        final String ikeCreateChildResp =
                "46b8eca1e0d72a189b9f8e0158e1c0a52e20242000000003000000cc210000b0"
                        + "e6bb78203dbe2189806c5cecef5040b8c4c0253895c7c0acea6483a1f0f72425"
                        + "77ab46e18d553329d4ae1bd31cf57eec6ec31ceb1f2ed6b1195cac98b4b97a25"
                        + "115d14c414e44dba8ebbdaf502e43f98a09036bee0ea2a621176300874a3eae8"
                        + "c988357255b4e5923928d335b0ef62a565333fae6a64c85ac30e7da34ceeade4"
                        + "1a161bcad0b51f8209ee1fdaf53d50359ad6b986ecd4290c9f69a34c64ddc0eb"
                        + "73b8f3231f3f4e057404c18d";
        final String ikeDeleteChildResp =
                "46b8eca1e0d72a189b9f8e0158e1c0a52e202520000000040000004c2a000030"
                        + "53d97806d48ce44e0d4e1adf1de36778f77c3823bfaf8186cc71d4dc73497099"
                        + "a9049e7be8a2013affd56ab7";

        ikeTunUtils.awaitReqAndInjectResp(
                IKE_DETERMINISTIC_INITIATOR_SPI,
                2 /* expectedMsgId */,
                true /* expectedUseEncap */,
                ikeUpdateSaResp);

        // If Kernel migration enabled, it will be used instead of MOBIKE-rekey
        // TODO (b/277939911): Decouple VCN CTS from IKE implementation behavior
        if (!mContext.getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_IPSEC_TUNNEL_MIGRATION)) {
            ikeTunUtils.awaitReqAndInjectResp(
                    IKE_DETERMINISTIC_INITIATOR_SPI,
                    3 /* expectedMsgId */,
                    true /* expectedUseEncap */,
                    ikeCreateChildResp);

            ikeTunUtils.awaitReqAndInjectResp(
                    IKE_DETERMINISTIC_INITIATOR_SPI,
                    4 /* expectedMsgId */,
                    true /* expectedUseEncap */,
                    ikeDeleteChildResp);
        }
    }

    private void injectAndVerifyIkeDpdPackets(
            @NonNull IkeTunUtils ikeTunUtils, PortPair localRemotePorts) throws Exception {
        // Generated by forcing IKE to use Test Mode (RandomnessFactory#mIsTestModeEnabled) and
        // capturing IKE packets with a live server.
        final String ikeDpdRequestHex =
                "46b8eca1e0d72a189b9f8e0158e1c0a52E202500000000000000004c00000030"
                        + "3A31D5FAC230FEA67246B0C1A049A28944C341301979EB7B52FC669274B77D5F"
                        + "A6CFE8D768CF390536436D08";

        byte[] ikeDpdRequest =
                IkeTunUtils.buildIkePacket(
                        REMOTE_ADDRESS,
                        LOCAL_ADDRESS,
                        localRemotePorts.dstPort,
                        localRemotePorts.srcPort,
                        true /* useEncap */,
                        hexStringToByteArray(ikeDpdRequestHex));

        ikeTunUtils.injectPacket(ikeDpdRequest);
        ikeTunUtils.awaitResp(
                IKE_DETERMINISTIC_INITIATOR_SPI,
                0 /* expectedMsgId */,
                true /* expectedUseEncap */);
    }

    private void verifyVcnSafeModeTimeoutOnTestNetwork(int subId, long timeoutMillis)
            throws Exception {
        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
            // Before the VCN starts, the test network should have NOT_VCN_MANAGED
            waitForExpectedUnderlyingNetworkWithCapabilities(
                    testNetworkWrapper,
                    true /* expectNotVcnManaged */,
                    false /* expectNotMetered */,
                    TestNetworkWrapper.NETWORK_CB_TIMEOUT_MS);
            verifyUnderlyingCellAndRunTest(subId, (subGrp, cellNetwork, cellNetworkCb) -> {
                final VcnSetupResult vcnSetupResult =
                    setupAndGetVcnNetwork(subGrp, cellNetwork, cellNetworkCb, testNetworkWrapper);

                // Once VCN starts, the test network should lose NOT_VCN_MANAGED
                waitForExpectedUnderlyingNetworkWithCapabilities(
                        testNetworkWrapper,
                        false /* expectNotVcnManaged */,
                        false /* expectNotMetered */,
                        TestNetworkWrapper.NETWORK_CB_TIMEOUT_MS);

                // After VCN has started up, wait for safemode to kick in and expect the
                // underlying Test Network to regain NOT_VCN_MANAGED.
                waitForExpectedUnderlyingNetworkWithCapabilities(
                        testNetworkWrapper,
                        true /* expectNotVcnManaged */,
                        false /* expectNotMetered */,
                        timeoutMillis);

                // Verify that VCN Network is also lost in safemode
                cellNetworkCb.waitForLostNetwork(vcnSetupResult.vcnNetwork);

                verifyVcnStatus(subGrp, VCN_STATUS_CODE_SAFE_MODE);

                mVcnManager.clearVcnConfig(subGrp);
            });
        }
    }

    private void setSafeModeTimeoutForCarrier(int subId, int timeoutSeconds) {
        final PersistableBundle carrierConfig = new PersistableBundle();
        carrierConfig.putInt(VcnManager.VCN_SAFE_MODE_TIMEOUT_SECONDS_KEY, timeoutSeconds);
        mCarrierConfigManager.overrideConfig(subId, carrierConfig);
    }

    @Test
    public void testVcnSafeModeOnTestNetwork_defaultTimeout() throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        verifyVcnSafeModeTimeoutOnTestNetwork(subId, SAFEMODE_TIMEOUT_MILLIS);
    }

    @RequiresFlagsEnabled(Flags.FLAG_SAFE_MODE_TIMEOUT_CONFIG)
    @Test
    public void testVcnSafeModeOnTestNetwork_overrideTimeout() throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        final int safeModeTimeoutSeconds = 5;
        final int gracePeriod = 5;

        final PersistableBundle oldCarrierConfig = mCarrierConfigManager.getConfigForSubId(subId);
        setSafeModeTimeoutForCarrier(subId, safeModeTimeoutSeconds);

        verifyVcnSafeModeTimeoutOnTestNetwork(
                subId, TimeUnit.SECONDS.toMillis(safeModeTimeoutSeconds + gracePeriod));

        mCarrierConfigManager.overrideConfig(subId, oldCarrierConfig);
    }

    private void verifyEnterSafeModeImmediately(VcnConfig vcnConfig, boolean isSafeModeExpected)
            throws Exception {
        final int subId = verifyAndGetValidDataSubId();
        final TestVcnStatusCallback callback = new TestVcnStatusCallback();

        // Override the safe mode timeout to be zero
        final PersistableBundle oldCarrierConfig = mCarrierConfigManager.getConfigForSubId(subId);
        setSafeModeTimeoutForCarrier(subId, 0);

        try (TestNetworkWrapper testNetworkWrapper =
                createTestNetworkWrapper(true /* isMetered */, subId, LOCAL_ADDRESS)) {
            verifyUnderlyingCellAndRunTest(subId, (subGrp, cellNetwork, cellNetworkCb) -> {
                mVcnManager.registerVcnStatusCallback(subGrp, INLINE_EXECUTOR, callback);
                mVcnManager.setVcnConfig(subGrp, vcnConfig);

                assertEquals(
                        VCN_STATUS_CODE_NOT_CONFIGURED, callback.awaitOnStatusChanged());
                assertEquals(VCN_STATUS_CODE_ACTIVE, callback.awaitOnStatusChanged());

                if (isSafeModeExpected) {
                    assertEquals(
                            VCN_STATUS_CODE_SAFE_MODE, callback.awaitOnStatusChanged());
                } else {
                    assertEquals(
                            VCN_STATUS_CODE_AWAIT_TIMEOUT, callback.awaitOnStatusChanged());
                }

                mVcnManager.clearVcnConfig(subGrp);
                mVcnManager.unregisterVcnStatusCallback(callback);
            });
        }

        // Reset Carrier Config
        mCarrierConfigManager.overrideConfig(subId, oldCarrierConfig);
    }

    private VcnConfig newVcnConfig(boolean isSafeModeEnabled) {
        final VcnGatewayConnectionConfig.Builder gatewayConfigBuilder =
                VcnGatewayConnectionConfigTest.buildVcnGatewayConnectionConfigBase()
                        .addExposedCapability(NetworkCapabilities.NET_CAPABILITY_MMS);

        if (!isSafeModeEnabled) {
            gatewayConfigBuilder.setSafeModeEnabled(false);
        }
        // Don't call setSafeModeEnabled since enabling safe mode should not be flag gated

        return new VcnConfig.Builder(mContext)
                .setIsTestModeProfile()
                .addGatewayConnectionConfig(gatewayConfigBuilder.build())
                .build();
    }

    @RequiresFlagsEnabled({Flags.FLAG_SAFE_MODE_TIMEOUT_CONFIG})
    @Test
    public void testEnterSafeModeImmediately_safeModeEnabled() throws Exception {
        verifyEnterSafeModeImmediately(
                newVcnConfig(true /* isSafeModeEnabled */), true /* isSafeModeExpected */);
    }

    @RequiresFlagsEnabled({Flags.FLAG_SAFE_MODE_CONFIG, Flags.FLAG_SAFE_MODE_TIMEOUT_CONFIG})
    @Test
    public void testEnterSafeModeImmediately_safeModeDisabled() throws Exception {
        verifyEnterSafeModeImmediately(
                newVcnConfig(false /* isSafeModeEnabled */), false /* isSafeModeExpected */);
    }
}