noxtls 0.2.10

TLS/DTLS protocol and connection state machine for the noxtls Rust stack.
Documentation
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
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
// Copyright (c) 2019-2026, Argenox Technologies LLC
// All rights reserved.
//
// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
//
// This file is part of the NoxTLS Library.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// Alternatively, this file may be used under the terms of a commercial
// license from Argenox Technologies LLC.
//
// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
// CONTACT: info@argenox.com

//! Regression tests for TLS record nonces and DTLS 1.2 reassembly semantics.
//!
//! Evidence for `VULNERABILITY_ANALYSIS_TLS_CRYPTO_MATRIX.md` (repository root).

use super::dtls::{
    noxtls_encode_dtls12_handshake_fragments, noxtls_open_dtls13_unified_aes128gcm_record,
    noxtls_open_dtls13_unified_aes128gcm_record_with_cid,
    noxtls_parse_dtls13_record_header_with_cid_len, noxtls_reassemble_dtls12_handshake_fragments,
    noxtls_seal_dtls13_unified_aes128gcm_record_with_cid, DtlsEpochReplayTracker,
};
use super::record::noxtls_build_record_nonce;
use super::{
    noxtls_parse_tls13_ocsp_staple_info, noxtls_verify_tls13_ocsp_staple, CipherSuite, Connection,
    HandshakeState, ProtectedRecord, RecordContentType, Tls13OcspStapleVerification,
    Tls13ServerIdentityKey, TlsRole, TlsVersion,
};
use noxtls_core::Error;
use noxtls_crypto::{noxtls_ffdhe_public_key, P256PrivateKey, RsaPrivateKey};
use noxtls_x509::{
    noxtls_p256_public_key_to_spki_der, noxtls_write_self_signed_certificate_p256_sha256,
};

/// Builds one DTLS 1.2 handshake fragment wire encoding for tests.
///
/// # Arguments
///
/// * `handshake_type` — Wire handshake type byte.
/// * `message_len` — Total reconstructed handshake body length.
/// * `message_seq` — DTLS `message_seq` for this message.
/// * `fragment_offset` — Byte offset of this fragment in the full message.
/// * `fragment_body` — Payload bytes for this fragment.
///
/// # Returns
///
/// Owned `header || body` bytes.
///
/// # Panics
///
/// This function does not panic.
#[must_use]
fn dtls12_test_fragment(
    handshake_type: u8,
    message_len: u32,
    message_seq: u16,
    fragment_offset: u32,
    fragment_body: &[u8],
) -> Vec<u8> {
    const HDR: usize = 12;
    let fragment_len = fragment_body.len() as u32;
    let mut v = Vec::with_capacity(HDR + fragment_body.len());
    v.push(handshake_type);
    v.push(((message_len >> 16) & 0xFF) as u8);
    v.push(((message_len >> 8) & 0xFF) as u8);
    v.push((message_len & 0xFF) as u8);
    v.extend_from_slice(&message_seq.to_be_bytes());
    v.push(((fragment_offset >> 16) & 0xFF) as u8);
    v.push(((fragment_offset >> 8) & 0xFF) as u8);
    v.push((fragment_offset & 0xFF) as u8);
    v.push(((fragment_len >> 16) & 0xFF) as u8);
    v.push(((fragment_len >> 8) & 0xFF) as u8);
    v.push((fragment_len & 0xFF) as u8);
    v.extend_from_slice(fragment_body);
    v
}

/// Verifies TLS 1.3 record nonce construction XORs the big-endian sequence into IV bytes 4..12.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_record_nonce_xor_matches_sequence() {
    let base = [0_u8; 12];
    let seq = 0x0102_0304_0506_0708_u64;
    let nonce = noxtls_build_record_nonce(&base, seq);
    let expected = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8];
    assert_eq!(nonce, expected);
}

fn tls12_finished_connection() -> Connection {
    tls12_finished_connection_for_suite(CipherSuite::TlsEcdheRsaWithAes128GcmSha256)
}

fn tls12_finished_connection_for_suite(suite: CipherSuite) -> Connection {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0xA5; 32])
        .expect("client hello should build");
    let server_hello = Connection::noxtls_build_server_hello(TlsVersion::Tls12, suite, &[0x5A; 32])
        .expect("server hello should build");
    connection
        .noxtls_recv_server_hello(&server_hello)
        .expect("server hello should parse");
    let pre_master_secret: Vec<u8> = (0_u8..48).collect();
    connection
        .noxtls_set_tls12_pre_master_secret(&pre_master_secret)
        .expect("pre-master secret should install");
    connection
        .noxtls_derive_handshake_secret()
        .expect("handshake secret should derive");
    let verify_data = connection
        .noxtls_compute_finished_verify_data()
        .expect("finished verify data should compute");
    connection
        .noxtls_finish(&verify_data)
        .expect("connection should finish");
    connection
}

/// Verifies TLS 1.2 master-secret derivation follows RFC 5246 PRF inputs.
#[test]
fn tls12_master_secret_matches_rfc5246_prf_vector() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0x11; 32])
        .expect("client hello should build");
    let server_hello = Connection::noxtls_build_server_hello(
        TlsVersion::Tls12,
        CipherSuite::TlsEcdheRsaWithAes128GcmSha256,
        &[0x22; 32],
    )
    .expect("server hello should build");
    connection
        .noxtls_recv_server_hello(&server_hello)
        .expect("server hello should parse");
    let pre_master_secret: Vec<u8> = (0_u8..48).collect();
    connection
        .noxtls_set_tls12_pre_master_secret(&pre_master_secret)
        .expect("pre-master secret should install");
    connection
        .noxtls_derive_handshake_secret()
        .expect("handshake secret should derive");

    let expected = [
        0xbf, 0x25, 0x51, 0xa8, 0x9a, 0x70, 0x0d, 0x54, 0x08, 0xb0, 0x99, 0xb3, 0xd7, 0x33, 0xfd,
        0x2a, 0x9f, 0x44, 0xa5, 0x9f, 0x47, 0xbe, 0xc7, 0x6b, 0x21, 0x9d, 0xe5, 0x79, 0x6d, 0x27,
        0x3c, 0x6f, 0x8e, 0x1c, 0xf4, 0x56, 0xa7, 0x68, 0x9d, 0x19, 0x5e, 0x98, 0x94, 0xb1, 0x93,
        0x82, 0x2f, 0xc3,
    ];
    assert_eq!(connection.noxtls_tls12_master_secret().unwrap(), expected);
}

/// Verifies real-world duplicate signature_algorithms entries are tolerated.
#[test]
fn tls13_client_hello_allows_duplicate_signature_algorithms() {
    fn ext(out: &mut Vec<u8>, ty: u16, data: &[u8]) {
        out.extend_from_slice(&ty.to_be_bytes());
        out.extend_from_slice(&(data.len() as u16).to_be_bytes());
        out.extend_from_slice(data);
    }

    let mut extensions = Vec::new();
    ext(&mut extensions, 0x002b, &[0x02, 0x03, 0x04]);
    ext(
        &mut extensions,
        0x000d,
        &[0x00, 0x06, 0x04, 0x03, 0x08, 0x05, 0x08, 0x05],
    );
    ext(
        &mut extensions,
        0x0033,
        &[
            0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
            0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
            0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
        ],
    );

    let mut body = Vec::new();
    body.extend_from_slice(&[0x03, 0x03]);
    body.extend_from_slice(&[0x42; 32]);
    body.push(0);
    body.extend_from_slice(&2_u16.to_be_bytes());
    body.extend_from_slice(&0x1302_u16.to_be_bytes());
    body.push(1);
    body.push(0);
    body.extend_from_slice(&(extensions.len() as u16).to_be_bytes());
    body.extend_from_slice(&extensions);

    let mut client_hello = vec![
        0x01,
        ((body.len() >> 16) & 0xff) as u8,
        ((body.len() >> 8) & 0xff) as u8,
        (body.len() & 0xff) as u8,
    ];
    client_hello.extend_from_slice(&body);

    let info = Connection::noxtls_parse_client_hello_info(&client_hello)
        .expect("duplicate signature schemes should be deduplicated, not rejected");
    assert_eq!(info.extensions.signature_algorithms, vec![0x0403, 0x0805]);
}

/// Verifies TLS 1.3 server role enforces the RFC 8446 ClientHello legacy_version value.
#[test]
fn tls13_server_rejects_invalid_client_hello_legacy_version() {
    let private_key =
        P256PrivateKey::from_bytes([0x11_u8; 32]).expect("p256 private key fixture should parse");
    let public_key = private_key.public_key().expect("p256 public key");
    let cert_der = noxtls_write_self_signed_certificate_p256_sha256(
        &[0x02],
        "localhost",
        "20200101000000Z",
        "20300101000000Z",
        &public_key,
        &private_key,
    )
    .expect("self-signed certificate should build");

    let mut client = Connection::noxtls_new(TlsVersion::Tls13);
    client.noxtls_set_tls13_client_offer_pq_key_shares(false);
    let mut client_hello = client
        .noxtls_send_client_hello(&[0x44_u8; 32])
        .expect("client hello should build");
    client_hello[4..6].copy_from_slice(&0x0301_u16.to_be_bytes());

    let parsed = Connection::noxtls_parse_client_hello_info(&client_hello)
        .expect("mutated client hello still parses");
    assert_eq!(parsed.legacy_version, 0x0301);

    let mut server = Connection::noxtls_new_tls13_server();
    server
        .noxtls_configure_tls13_server_identity(
            &[cert_der],
            Tls13ServerIdentityKey::P256(private_key),
        )
        .expect("server identity should configure");
    let err = server
        .noxtls_accept_tls13_client_hello(&client_hello, &[0x33_u8; 32])
        .expect_err("invalid TLS 1.3 ClientHello legacy_version must be rejected");
    assert!(err
        .to_string()
        .contains("tls13 client hello has invalid legacy_version"));
}

/// Verifies TLS 1.2 AES-GCM packets carry the RFC 5288 explicit nonce on the wire.
#[test]
fn tls12_gcm_packet_carries_explicit_nonce() {
    let mut connection = tls12_finished_connection();
    let plaintext = b"tls12 explicit nonce payload";
    let packet = connection
        .noxtls_seal_tls12_record_packet(plaintext, RecordContentType::ApplicationData)
        .expect("tls12 packet should seal");

    assert_eq!(&packet[..3], &[0x17, 0x03, 0x03]);
    let payload_len = u16::from_be_bytes([packet[3], packet[4]]) as usize;
    assert_eq!(payload_len, 8 + plaintext.len() + 16);
    assert_eq!(&packet[5..13], &0_u64.to_be_bytes());

    let (content_type, recovered) = connection
        .noxtls_open_own_tls12_record_packet(&packet, 0)
        .expect("tls12 packet should open");
    assert_eq!(content_type, RecordContentType::ApplicationData);
    assert_eq!(recovered, plaintext);
}

#[test]
fn tls12_c_reference_aead_suite_records_roundtrip() {
    let suites = [
        CipherSuite::TlsEcdheEcdsaWithChacha20Poly1305Sha256,
        CipherSuite::TlsDheRsaWithChacha20Poly1305Sha256,
        CipherSuite::TlsDheRsaWithAes128GcmSha256,
        CipherSuite::TlsDheRsaWithAes256GcmSha384,
        CipherSuite::TlsRsaWithAes128GcmSha256,
        CipherSuite::TlsRsaWithAes256GcmSha384,
        CipherSuite::TlsRsaWithAes128CcmSha256,
        CipherSuite::TlsRsaWithAes256CcmSha256,
        CipherSuite::TlsRsaWithAes128Ccm8Sha256,
        CipherSuite::TlsRsaWithAes256Ccm8Sha256,
        CipherSuite::TlsDheRsaWithAes128CcmSha256,
        CipherSuite::TlsDheRsaWithAes256CcmSha256,
        CipherSuite::TlsDheRsaWithAes128Ccm8Sha256,
        CipherSuite::TlsDheRsaWithAes256Ccm8Sha256,
        CipherSuite::TlsPskWithAes128Ccm8Sha256,
        CipherSuite::TlsEcjpakeWithAes128Ccm8Sha256,
    ];

    for suite in suites {
        let mut connection = tls12_finished_connection_for_suite(suite);
        let plaintext = b"tls12 c reference suite payload";
        let packet = connection
            .noxtls_seal_tls12_record_packet(plaintext, RecordContentType::ApplicationData)
            .expect("tls12 packet should seal");
        let (content_type, recovered) = connection
            .noxtls_open_own_tls12_record_packet(&packet, 0)
            .expect("tls12 packet should open");
        assert_eq!(content_type, RecordContentType::ApplicationData);
        assert_eq!(recovered, plaintext);
    }
}

fn tls12_handshake_message(message_type: u8, body: &[u8]) -> Vec<u8> {
    let mut message = Vec::with_capacity(4 + body.len());
    message.push(message_type);
    message.push(((body.len() >> 16) & 0xff) as u8);
    message.push(((body.len() >> 8) & 0xff) as u8);
    message.push((body.len() & 0xff) as u8);
    message.extend_from_slice(body);
    message
}

fn tls12_minimal_certificate_message() -> Vec<u8> {
    tls12_handshake_message(11, &[0x00, 0x00, 0x04, 0x00, 0x00, 0x01, 0x30])
}

fn tls12_server_hello_done_message() -> Vec<u8> {
    tls12_handshake_message(14, &[])
}

fn tls12_finished_message() -> Vec<u8> {
    tls12_handshake_message(20, &[0xAA; 12])
}

fn tls12_server_key_exchange_message(body: &[u8]) -> Vec<u8> {
    tls12_handshake_message(12, body)
}

fn tls12_client_key_exchange_message(body: &[u8]) -> Vec<u8> {
    tls12_handshake_message(16, body)
}

fn tls12_server_connection_after_flight(
    suite: CipherSuite,
    server_key_exchange: Option<&[u8]>,
) -> Connection {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0x10; 32])
        .expect("client hello should build");
    let server_hello = Connection::noxtls_build_server_hello(TlsVersion::Tls12, suite, &[0x20; 32])
        .expect("server hello should build");
    let certificate = tls12_minimal_certificate_message();
    let done = tls12_server_hello_done_message();
    let mut messages = vec![server_hello, certificate];
    if let Some(body) = server_key_exchange {
        messages.push(tls12_server_key_exchange_message(body));
    }
    messages.push(done);
    connection
        .noxtls_process_tls12_server_handshake_flight(&messages)
        .expect("tls12 server flight should process");
    connection
}

#[test]
fn tls12_suite_specific_server_key_exchange_shapes_are_enforced() {
    let ecdhe_body = [0x03, 0x00, 0x17, 0x01, 0x04, 0x04, 0x03, 0x00, 0x01, 0xAA];
    tls12_server_connection_after_flight(
        CipherSuite::TlsEcdheEcdsaWithChacha20Poly1305Sha256,
        Some(&ecdhe_body),
    );

    let dhe_body = [
        0x00, 0x01, 0x17, 0x00, 0x01, 0x05, 0x00, 0x01, 0x11, 0x08, 0x04, 0x00, 0x01, 0xAA,
    ];
    tls12_server_connection_after_flight(
        CipherSuite::TlsDheRsaWithAes128GcmSha256,
        Some(&dhe_body),
    );

    tls12_server_connection_after_flight(CipherSuite::TlsRsaWithAes128GcmSha256, None);
    tls12_server_connection_after_flight(
        CipherSuite::TlsPskWithAes128Ccm8Sha256,
        Some(&[0x00, 0x00]),
    );
    tls12_server_connection_after_flight(
        CipherSuite::TlsEcjpakeWithAes128Ccm8Sha256,
        Some(&[0x01]),
    );
}

#[test]
fn tls12_rsa_suite_rejects_unexpected_server_key_exchange() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0x10; 32])
        .expect("client hello should build");
    let server_hello = Connection::noxtls_build_server_hello(
        TlsVersion::Tls12,
        CipherSuite::TlsRsaWithAes128GcmSha256,
        &[0x20; 32],
    )
    .expect("server hello should build");
    let messages = vec![
        server_hello,
        tls12_minimal_certificate_message(),
        tls12_server_key_exchange_message(&[0x00, 0x00]),
        tls12_server_hello_done_message(),
    ];

    let error = connection
        .noxtls_process_tls12_server_handshake_flight(&messages)
        .expect_err("rsa key transport must not accept server key exchange");
    assert!(error.to_string().contains("rsa key transport must omit"));
}

#[test]
fn tls12_suite_specific_client_key_exchange_shapes_are_enforced() {
    let cases: &[(CipherSuite, Option<&[u8]>, &[u8])] = &[
        (
            CipherSuite::TlsRsaWithAes128GcmSha256,
            None,
            &[0x00, 0x02, 0xAA, 0xBB],
        ),
        (
            CipherSuite::TlsEcdheEcdsaWithChacha20Poly1305Sha256,
            Some(&[0x03, 0x00, 0x17, 0x01, 0x04, 0x04, 0x03, 0x00, 0x01, 0xAA]),
            &[0x01, 0x04],
        ),
        (
            CipherSuite::TlsDheRsaWithAes128GcmSha256,
            Some(&[
                0x00, 0x01, 0x17, 0x00, 0x01, 0x05, 0x00, 0x01, 0x11, 0x08, 0x04, 0x00, 0x01, 0xAA,
            ]),
            &[0x00, 0x01, 0x22],
        ),
        (
            CipherSuite::TlsPskWithAes128Ccm8Sha256,
            Some(&[0x00, 0x00]),
            &[0x00, 0x03, b'p', b's', b'k'],
        ),
        (
            CipherSuite::TlsEcjpakeWithAes128Ccm8Sha256,
            Some(&[0x01]),
            &[0x02],
        ),
    ];

    for (suite, server_key_exchange, client_key_exchange) in cases {
        let mut connection = tls12_server_connection_after_flight(*suite, *server_key_exchange);
        connection
            .noxtls_recv_tls12_change_cipher_spec()
            .expect("change cipher spec should be accepted");
        let messages = vec![
            tls12_client_key_exchange_message(client_key_exchange),
            tls12_finished_message(),
        ];
        connection
            .noxtls_process_tls12_client_handshake_flight(&messages)
            .expect("tls12 client flight should process");
        assert_eq!(connection.state, HandshakeState::Finished);
    }
}

#[test]
fn tls12_dhe_installs_pre_master_from_parsed_key_exchange_values() {
    let prime = [0x17_u8];
    let generator = [0x05_u8];
    let server_private = [0x06_u8];
    let client_private = [0x0F_u8];
    let server_public = noxtls_ffdhe_public_key(&server_private, &generator, &prime)
        .expect("server public key should compute");
    let client_public = noxtls_ffdhe_public_key(&client_private, &generator, &prime)
        .expect("client public key should compute");
    assert_eq!(server_public, vec![0x08]);
    assert_eq!(client_public, vec![0x13]);

    let dhe_body = [
        0x00,
        0x01,
        prime[0],
        0x00,
        0x01,
        generator[0],
        0x00,
        0x01,
        server_public[0],
        0x08,
        0x04,
        0x00,
        0x01,
        0xAA,
    ];
    let mut connection = tls12_server_connection_after_flight(
        CipherSuite::TlsDheRsaWithAes128GcmSha256,
        Some(&dhe_body),
    );
    connection
        .noxtls_install_tls12_dhe_pre_master_secret_from_server_key_exchange(&client_private)
        .expect("client-side dhe pre-master should install");
    let client_master = connection
        .noxtls_derive_handshake_secret()
        .expect("client-side dhe master should derive");

    let mut server_connection = tls12_server_connection_after_flight(
        CipherSuite::TlsDheRsaWithAes128GcmSha256,
        Some(&dhe_body),
    );
    server_connection
        .noxtls_recv_tls12_change_cipher_spec()
        .expect("change cipher spec should be accepted");
    server_connection
        .noxtls_process_tls12_client_handshake_flight(&[
            tls12_client_key_exchange_message(&[0x00, 0x01, client_public[0]]),
            tls12_finished_message(),
        ])
        .expect("tls12 client flight should process");
    server_connection
        .noxtls_install_tls12_dhe_pre_master_secret_from_client_key_exchange(&server_private)
        .expect("server-side dhe pre-master should install");
    let server_master = server_connection
        .noxtls_derive_handshake_secret()
        .expect("server-side dhe master should derive");
    assert_eq!(client_master, server_master);
}

#[test]
fn tls12_rsa_key_transport_installs_fallback_pre_master_on_decrypt_failure() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0xA7; 32])
        .expect("client hello should build");
    let server_hello = Connection::noxtls_build_server_hello(
        TlsVersion::Tls12,
        CipherSuite::TlsRsaWithAes128GcmSha256,
        &[0x5C; 32],
    )
    .expect("server hello should build");
    connection
        .noxtls_recv_server_hello(&server_hello)
        .expect("server hello should parse");

    let private_key = RsaPrivateKey::from_u128(3233, 2753);
    let mut fallback = [0x42_u8; 48];
    fallback[0] = 0x03;
    fallback[1] = 0x03;
    let accepted = connection
        .noxtls_set_tls12_rsa_pre_master_secret_from_encrypted(&private_key, &[0x00], &fallback)
        .expect("rsa fallback pre-master should install");
    assert!(!accepted);

    connection
        .noxtls_derive_handshake_secret()
        .expect("handshake secret should derive");
    let verify_data = connection
        .noxtls_compute_finished_verify_data()
        .expect("finished verify data should compute");
    connection
        .noxtls_finish(&verify_data)
        .expect("connection should finish");

    let packet = connection
        .noxtls_seal_tls12_record_packet(b"rsa payload", RecordContentType::ApplicationData)
        .expect("rsa tls12 packet should seal");
    let (_content_type, recovered) = connection
        .noxtls_open_own_tls12_record_packet(&packet, 0)
        .expect("rsa tls12 packet should open");
    assert_eq!(recovered, b"rsa payload");
}

#[test]
fn tls12_rsa_key_transport_installs_pre_master_from_parsed_client_key_exchange() {
    let mut connection =
        tls12_server_connection_after_flight(CipherSuite::TlsRsaWithAes128GcmSha256, None);
    connection
        .noxtls_recv_tls12_change_cipher_spec()
        .expect("change cipher spec should be accepted");
    let messages = vec![
        tls12_client_key_exchange_message(&[0x00, 0x02, 0xAA, 0xBB]),
        tls12_finished_message(),
    ];
    connection
        .noxtls_process_tls12_client_handshake_flight(&messages)
        .expect("tls12 client flight should process");

    let private_key = RsaPrivateKey::from_u128(3233, 2753);
    let mut fallback = [0x24_u8; 48];
    fallback[0] = 0x03;
    fallback[1] = 0x03;
    let accepted = connection
        .noxtls_install_tls12_rsa_pre_master_secret_from_client_key_exchange(
            &private_key,
            &fallback,
        )
        .expect("parsed rsa pre-master should install fallback");
    assert!(!accepted);
    connection
        .noxtls_derive_handshake_secret()
        .expect("handshake secret should derive");
}

#[test]
fn tls12_psk_pre_master_secret_matches_rfc4279_shape() {
    let pre_master = Connection::noxtls_build_tls12_psk_pre_master_secret(b"psk")
        .expect("psk pre-master should build");
    assert_eq!(
        pre_master,
        vec![0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, b'p', b's', b'k']
    );
}

#[test]
fn tls12_psk_suite_derives_record_keys_from_rfc4279_pre_master_secret() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0xA6; 32])
        .expect("client hello should build");
    let server_hello = Connection::noxtls_build_server_hello(
        TlsVersion::Tls12,
        CipherSuite::TlsPskWithAes128Ccm8Sha256,
        &[0x5B; 32],
    )
    .expect("server hello should build");
    connection
        .noxtls_recv_server_hello(&server_hello)
        .expect("server hello should parse");
    connection
        .noxtls_set_tls12_psk_pre_master_secret(b"psk")
        .expect("psk pre-master should install");
    connection
        .noxtls_derive_handshake_secret()
        .expect("handshake secret should derive");
    let verify_data = connection
        .noxtls_compute_finished_verify_data()
        .expect("finished verify data should compute");
    connection
        .noxtls_finish(&verify_data)
        .expect("connection should finish");

    let packet = connection
        .noxtls_seal_tls12_record_packet(b"psk payload", RecordContentType::ApplicationData)
        .expect("psk tls12 packet should seal");
    let (_content_type, recovered) = connection
        .noxtls_open_own_tls12_record_packet(&packet, 0)
        .expect("psk tls12 packet should open");
    assert_eq!(recovered, b"psk payload");
}

/// Verifies removing the TLS 1.2 explicit nonce makes the AEAD packet malformed.
#[test]
fn tls12_gcm_packet_rejects_missing_explicit_nonce() {
    let mut connection = tls12_finished_connection();
    let packet = connection
        .noxtls_seal_tls12_record_packet(b"x", RecordContentType::ApplicationData)
        .expect("tls12 packet should seal");
    let mut truncated = packet[..5].to_vec();
    truncated.extend_from_slice(&packet[13..]);
    let payload_len = (truncated.len() - 5) as u16;
    truncated[3..5].copy_from_slice(&payload_len.to_be_bytes());

    let error = connection
        .noxtls_open_own_tls12_record_packet(&truncated, 0)
        .expect_err("missing explicit nonce should fail");
    assert_eq!(format!("{error}"), "tls12 record payload too short");
}

/// Verifies non-overlapping DTLS 1.2 fragments reassemble to the original body.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn dtls12_reassemble_non_overlapping_round_trip() {
    let body = b"hello-dtls-reassembly".to_vec();
    let frags = noxtls_encode_dtls12_handshake_fragments(0x01, 0_u16, &body, 7).expect("encode");
    let (_, _, got) =
        noxtls_reassemble_dtls12_handshake_fragments(&frags, 65_536).expect("reassemble");
    assert_eq!(got, body);
}

/// Documents that overlapping fragment ranges keep the **last** applied bytes (defense / spec review).
///
/// # Panics
///
/// This function does not panic.
#[test]
fn dtls12_reassemble_overlapping_last_write_wins() {
    let message_len = 4_u32;
    let seq = 3_u16;
    let f1 = dtls12_test_fragment(0x0B, message_len, seq, 0, b"AA");
    let f2 = dtls12_test_fragment(0x0B, message_len, seq, 0, b"BB");
    let f3 = dtls12_test_fragment(0x0B, message_len, seq, 2, b"CC");
    let got =
        noxtls_reassemble_dtls12_handshake_fragments(&[f1, f2, f3], 65_536).expect("reassemble");
    assert_eq!(got.2, b"BBCC".as_slice());
}

/// Verifies TLS 1.2 ClientHello and ServerHello negotiate RFC 5746 initially.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls12_secure_renegotiation_initial_handshake_uses_empty_binding() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    let client_hello = connection
        .noxtls_send_client_hello(&[0x51_u8; 32])
        .expect("client hello should build");
    let parsed =
        Connection::noxtls_parse_client_hello_info(&client_hello).expect("client hello parses");
    assert_eq!(
        parsed.extensions.secure_renegotiation_info,
        Some(Vec::new())
    );

    let server_hello = Connection::noxtls_build_server_hello(
        TlsVersion::Tls12,
        CipherSuite::TlsEcdheRsaWithAes128GcmSha256,
        &[0x52_u8; 32],
    )
    .expect("server hello should build");
    connection
        .noxtls_recv_server_hello(&server_hello)
        .expect("server hello should accept empty renegotiation_info");
    assert!(connection.noxtls_tls12_secure_renegotiation_negotiated());
}

/// Verifies TLS 1.2 rejects a ServerHello that omits RFC 5746 after client offer.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls12_secure_renegotiation_rejects_missing_server_extension() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls12);
    connection
        .noxtls_send_client_hello(&[0x53_u8; 32])
        .expect("client hello should build");
    let legacy_server_hello = [0x02, 0xC0, 0x2F];

    let error = connection
        .noxtls_recv_server_hello(&legacy_server_hello)
        .expect_err("missing renegotiation_info should fail");
    match error {
        Error::ParseFailure(message) => {
            assert_eq!(
                message,
                "tls12 server hello missing renegotiation_info extension"
            );
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.2 secure renegotiation carries previous Finished verify_data.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls12_secure_renegotiation_binds_prior_verify_data() {
    let mut connection = tls12_finished_connection();
    let client_verify = [0xA1_u8; 12];
    let server_verify = [0xB2_u8; 12];
    connection
        .noxtls_set_tls12_secure_renegotiation_verify_data_for_test(&client_verify, &server_verify)
        .expect("verify data fixture should install");

    let client_hello = connection
        .noxtls_start_tls12_secure_renegotiation(&[0x54_u8; 32])
        .expect("renegotiation client hello should build");
    let parsed =
        Connection::noxtls_parse_client_hello_info(&client_hello).expect("client hello parses");
    assert_eq!(
        parsed.extensions.secure_renegotiation_info,
        Some(client_verify.to_vec())
    );

    let server_hello = Connection::noxtls_build_tls12_server_hello_with_secure_renegotiation(
        CipherSuite::TlsEcdheRsaWithAes128GcmSha256,
        &[0x55_u8; 32],
        &client_verify,
        &server_verify,
    )
    .expect("renegotiating server hello should build");
    connection
        .noxtls_recv_server_hello(&server_hello)
        .expect("renegotiation binding should validate");
}

/// Verifies TLS 1.2 secure renegotiation rejects mismatched server binding.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls12_secure_renegotiation_rejects_mismatched_binding() {
    let mut connection = tls12_finished_connection();
    let client_verify = [0xC1_u8; 12];
    let server_verify = [0xD2_u8; 12];
    connection
        .noxtls_set_tls12_secure_renegotiation_verify_data_for_test(&client_verify, &server_verify)
        .expect("verify data fixture should install");
    connection
        .noxtls_start_tls12_secure_renegotiation(&[0x56_u8; 32])
        .expect("renegotiation client hello should build");

    let server_hello = Connection::noxtls_build_tls12_server_hello_with_secure_renegotiation(
        CipherSuite::TlsEcdheRsaWithAes128GcmSha256,
        &[0x57_u8; 32],
        &client_verify,
        &[0xEE_u8; 12],
    )
    .expect("renegotiating server hello should build");
    let error = connection
        .noxtls_recv_server_hello(&server_hello)
        .expect_err("mismatched renegotiation binding should fail");
    match error {
        Error::ParseFailure(message) => {
            assert_eq!(
                message,
                "tls12 server hello renegotiation_info verify_data mismatch"
            );
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.3 interop profile emits classical-only offers used for live HTTPS compatibility.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_client_hello_interop_profile_uses_expected_groups_and_schemes() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    connection.noxtls_set_tls13_client_offer_pq_key_shares(false);
    connection.noxtls_set_tls13_client_offer_mldsa_signature(false);
    connection
        .noxtls_set_tls13_client_cipher_suites(&[CipherSuite::TlsAes128GcmSha256])
        .expect("set tls13 cipher override");
    let client_hello = connection
        .noxtls_send_client_hello(&[0x11_u8; 32])
        .expect("build client hello");

    let parsed =
        Connection::noxtls_parse_client_hello_info(&client_hello).expect("parse client hello");

    assert_eq!(
        parsed.offered_cipher_suites,
        vec![CipherSuite::TlsAes128GcmSha256]
    );
    assert_eq!(parsed.extensions.key_share_groups, vec![0x001D, 0x0017]);
    assert!(parsed.extensions.supported_versions.contains(&0x0304));
    assert!(parsed.extensions.supported_versions.contains(&0x0303));
    assert!(!parsed.extensions.signature_algorithms.contains(&0x0905));
}

/// Verifies TLS 1.3 encrypted handshake records remain openable after EncryptedExtensions processing.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_open_record_allowed_in_server_certificate_verified_state() {
    let states = [
        HandshakeState::KeysDerived,
        HandshakeState::ServerEncryptedExtensionsReceived,
        HandshakeState::ServerCertificateRequestReceived,
        HandshakeState::ServerCertificateReceived,
        HandshakeState::ServerCertificateVerified,
    ];
    for state in states {
        let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
        connection.state = state;
        let record = ProtectedRecord {
            sequence: 0,
            ciphertext: vec![0_u8; 1],
            tag: [0_u8; 16],
        };

        let result = connection.noxtls_open_record(&record, &[]);
        assert!(result.is_err());
        let error = result.expect_err("record opening should fail without traffic keys");
        if let Error::StateError(message) = error {
            assert_ne!(message, "cannot open record before handshake noxtls_finish");
        }
    }
}

/// Verifies TLS 1.3 application traffic activation is gated until Finished state.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_application_key_activation_requires_finished_state() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    let error = connection
        .noxtls_activate_tls13_application_traffic_keys()
        .expect_err("activation should fail before Finished");
    match error {
        Error::StateError(message) => {
            assert_eq!(
                message,
                "application traffic keys can only be activated in finished state"
            );
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.3 PSK ClientHello can explicitly offer early_data.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_psk_client_hello_can_offer_early_data() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    connection.noxtls_set_tls13_client_offer_pq_key_shares(false);
    connection.noxtls_set_tls13_client_offer_mldsa_signature(false);

    let client_hello = connection
        .noxtls_send_client_hello_with_psk_and_early_data(
            &[0x44_u8; 32],
            b"ticket-identity",
            0,
            b"resumption psk fixture",
        )
        .expect("early-data PSK ClientHello should build");

    let parsed = Connection::noxtls_parse_client_hello_info(&client_hello)
        .expect("client hello should parse");
    assert!(parsed.extensions.early_data_offered);
}

/// Verifies TLS 1.3 EndOfEarlyData is accepted only after early_data acceptance.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_end_of_early_data_requires_accepted_early_data() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    let message = Connection::noxtls_build_tls13_end_of_early_data();

    connection.state = HandshakeState::ServerEncryptedExtensionsReceived;
    let error = connection
        .noxtls_recv_tls13_end_of_early_data(&message)
        .expect_err("EndOfEarlyData without accepted early_data should fail");

    match error {
        Error::StateError(message) => {
            assert_eq!(message, "tls13 EndOfEarlyData requires accepted early_data");
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.3 EndOfEarlyData is empty, transcript-tracked, and closes 0-RTT.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_end_of_early_data_closes_early_data_phase() {
    let psk = b"resumption psk fixture";
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    connection.noxtls_set_tls13_client_offer_pq_key_shares(false);
    connection.noxtls_set_tls13_client_offer_mldsa_signature(false);
    connection
        .noxtls_send_client_hello_with_psk_and_early_data(
            &[0x45_u8; 32],
            b"ticket-identity",
            0,
            psk,
        )
        .expect("early-data PSK ClientHello should build");
    let record = connection
        .noxtls_seal_tls13_early_data_record(psk, b"GET /", &[], 0)
        .expect("early data record should seal before EoED");

    connection.state = HandshakeState::ServerHelloReceived;
    let encrypted_extensions =
        Connection::noxtls_build_encrypted_extensions_with_alpn_and_early_data(None, true)
            .expect("encrypted extensions should build");
    connection
        .noxtls_recv_encrypted_extensions(&encrypted_extensions)
        .expect("early_data acceptance should parse");

    let end_of_early_data = Connection::noxtls_build_tls13_end_of_early_data();
    connection
        .noxtls_recv_tls13_end_of_early_data(&end_of_early_data)
        .expect("EndOfEarlyData should parse after acceptance");
    assert!(connection.noxtls_tls13_end_of_early_data_seen());

    connection.state = HandshakeState::ClientHelloSent;
    let error = connection
        .noxtls_open_tls13_early_data_record(psk, &record, &[])
        .expect_err("early data after EndOfEarlyData should fail");
    match error {
        Error::StateError(message) => {
            assert_eq!(
                message,
                "tls13 early-data cannot be opened after EndOfEarlyData"
            );
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.3 EndOfEarlyData rejects non-empty handshake bodies.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_end_of_early_data_rejects_non_empty_body() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    connection.noxtls_set_tls13_client_offer_pq_key_shares(false);
    connection.noxtls_set_tls13_client_offer_mldsa_signature(false);
    connection
        .noxtls_send_client_hello_with_psk_and_early_data(
            &[0x46_u8; 32],
            b"ticket-identity",
            0,
            b"resumption psk fixture",
        )
        .expect("early-data PSK ClientHello should build");
    connection.state = HandshakeState::ServerHelloReceived;
    let encrypted_extensions =
        Connection::noxtls_build_encrypted_extensions_with_alpn_and_early_data(None, true)
            .expect("encrypted extensions should build");
    connection
        .noxtls_recv_encrypted_extensions(&encrypted_extensions)
        .expect("early_data acceptance should parse");

    let malformed = [0x05, 0x00, 0x00, 0x01, 0x00];
    let error = connection
        .noxtls_recv_tls13_end_of_early_data(&malformed)
        .expect_err("non-empty EndOfEarlyData should fail");
    match error {
        Error::ParseFailure(message) => {
            assert_eq!(message, "EndOfEarlyData body must be empty");
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.3 ClientHello advertises RFC 7250 raw-public-key certificate types.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_client_hello_advertises_raw_public_key_certificate_types() {
    let mut connection = Connection::noxtls_new(TlsVersion::Tls13);
    connection.noxtls_set_tls13_client_offer_pq_key_shares(false);
    connection.noxtls_set_tls13_client_offer_mldsa_signature(false);
    connection.noxtls_set_tls13_raw_public_keys_enabled(true);

    let client_hello = connection
        .noxtls_send_client_hello(&[0x47_u8; 32])
        .expect("client hello should build");
    let parsed =
        Connection::noxtls_parse_client_hello_info(&client_hello).expect("client hello parses");

    assert_eq!(parsed.extensions.client_certificate_types, vec![0x02]);
    assert_eq!(parsed.extensions.server_certificate_types, vec![0x02, 0x00]);
}

/// Verifies a raw-public-key server identity requires the client RFC 7250 offer.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_raw_public_key_server_requires_client_offer() {
    let private_key =
        P256PrivateKey::from_bytes([0x12_u8; 32]).expect("p256 private key fixture should parse");
    let public_key = private_key.public_key().expect("p256 public key");
    let spki = noxtls_p256_public_key_to_spki_der(&public_key).expect("p256 spki should encode");

    let mut client = Connection::noxtls_new(TlsVersion::Tls13);
    client.noxtls_set_tls13_client_offer_pq_key_shares(false);
    client.noxtls_set_tls13_client_offer_mldsa_signature(false);
    let client_hello = client
        .noxtls_send_client_hello(&[0x48_u8; 32])
        .expect("client hello should build");

    let mut server = Connection::noxtls_new_tls13_server();
    server
        .noxtls_configure_tls13_server_raw_public_key_identity(
            &spki,
            Tls13ServerIdentityKey::P256(private_key),
        )
        .expect("raw public key identity should configure");

    let error = server
        .noxtls_accept_tls13_client_hello(&client_hello, &[0x49_u8; 32])
        .expect_err("server should reject missing raw-public-key offer");
    match error {
        Error::ParseFailure(message) => {
            assert_eq!(
                message,
                "client hello did not offer raw public key server certificates"
            );
        }
        other => panic!("unexpected error variant: {other:?}"),
    }
}

/// Verifies TLS 1.3 server-role handshake can use RFC 7250 raw public keys.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_server_role_raw_public_key_handshake_roundtrip() {
    let private_key =
        P256PrivateKey::from_bytes([0x13_u8; 32]).expect("p256 private key fixture should parse");
    let public_key = private_key.public_key().expect("p256 public key");
    let spki = noxtls_p256_public_key_to_spki_der(&public_key).expect("p256 spki should encode");

    let mut client = Connection::noxtls_new(TlsVersion::Tls13);
    client.noxtls_set_tls13_client_offer_pq_key_shares(false);
    client.noxtls_set_tls13_client_offer_mldsa_signature(false);
    client
        .noxtls_set_tls13_expected_server_raw_public_key(&spki)
        .expect("expected raw public key should configure");
    client
        .noxtls_set_tls13_client_cipher_suites(&[CipherSuite::TlsAes128GcmSha256])
        .expect("set client cipher suites");
    let client_hello = client
        .noxtls_send_client_hello(&[0x4A_u8; 32])
        .expect("client hello should build");

    let mut server = Connection::noxtls_new_tls13_server();
    server
        .noxtls_configure_tls13_server_raw_public_key_identity(
            &spki,
            Tls13ServerIdentityKey::P256(private_key),
        )
        .expect("raw public key identity should configure");
    let server_hello = server
        .noxtls_accept_tls13_client_hello(&client_hello, &[0x4B_u8; 32])
        .expect("server should accept client hello");

    client
        .noxtls_recv_server_hello(&server_hello)
        .expect("client should process server hello");
    server
        .noxtls_derive_handshake_secret()
        .expect("server should derive handshake secret");
    let flight_packet = server
        .noxtls_build_tls13_server_handshake_flight()
        .expect("server raw-public-key flight should build");
    let flight_aad = Connection::noxtls_tls13_packet_header_aad(&flight_packet)
        .expect("server flight packet header should parse");
    client
        .noxtls_process_tls13_server_encrypted_handshake_flight(
            core::slice::from_ref(&flight_packet),
            &flight_aad,
        )
        .expect("client should process raw-public-key server flight");

    assert_eq!(client.state, HandshakeState::Finished);
}

/// Verifies TLS 1.3 server-role APIs complete a handshake roundtrip with a noxtls client.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_server_role_handshake_roundtrip_with_noxtls_client() {
    let private_key =
        P256PrivateKey::from_bytes([0x11_u8; 32]).expect("p256 private key fixture should parse");
    let public_key = private_key.public_key().expect("p256 public key");
    let cert_der = noxtls_write_self_signed_certificate_p256_sha256(
        &[0x01],
        "localhost",
        "20200101000000Z",
        "20300101000000Z",
        &public_key,
        &private_key,
    )
    .expect("self-signed certificate should build");

    let mut client = Connection::noxtls_new(TlsVersion::Tls13);
    client.noxtls_set_tls13_client_offer_pq_key_shares(false);
    client
        .noxtls_set_tls13_client_cipher_suites(&[CipherSuite::TlsAes128GcmSha256])
        .expect("set client cipher suites");
    let client_hello = client
        .noxtls_send_client_hello(&[0x22_u8; 32])
        .expect("client hello should build");

    let mut server = Connection::noxtls_new_tls13_server();
    server
        .noxtls_configure_tls13_server_identity(
            &[cert_der],
            Tls13ServerIdentityKey::P256(private_key),
        )
        .expect("server identity should configure");
    let server_hello = server
        .noxtls_accept_tls13_client_hello(&client_hello, &[0x33_u8; 32])
        .expect("server should accept client hello");

    client
        .noxtls_recv_server_hello(&server_hello)
        .expect("client should process server hello");
    server
        .noxtls_derive_handshake_secret()
        .expect("server should derive handshake secret");
    let flight_packet = server
        .noxtls_build_tls13_server_handshake_flight()
        .expect("server handshake flight should build");
    let flight_aad = Connection::noxtls_tls13_packet_header_aad(&flight_packet)
        .expect("server flight packet header should parse");
    client
        .noxtls_process_tls13_server_encrypted_handshake_flight(
            core::slice::from_ref(&flight_packet),
            &flight_aad,
        )
        .expect("client should process encrypted server flight");
    assert_eq!(client.state, HandshakeState::Finished);

    let client_finished = client
        .noxtls_prepare_tls13_client_finished_message()
        .expect("client finished should build");
    let inner_len = client_finished
        .len()
        .checked_add(1)
        .expect("client finished inner length");
    let payload_len = inner_len
        .checked_add(16)
        .expect("client finished ciphertext length");
    let mut client_finished_aad = [0_u8; 5];
    client_finished_aad[0] = RecordContentType::ApplicationData.to_u8();
    client_finished_aad[1] = 0x03;
    client_finished_aad[2] = 0x03;
    client_finished_aad[3..5].copy_from_slice(&(payload_len as u16).to_be_bytes());
    let client_finished_packet = client
        .noxtls_seal_tls13_record_packet(
            &client_finished,
            RecordContentType::Handshake.to_u8(),
            &client_finished_aad,
            0,
        )
        .expect("client finished packet should seal");
    server
        .noxtls_recv_client_finished_packet(&client_finished_packet)
        .expect("server should accept client finished");
    assert_eq!(server.state, HandshakeState::Finished);
}

/// Verifies TLS 1.3 server compatibility CCS uses the exact middlebox wire record.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_server_compatibility_ccs_record_matches_wire_format() {
    assert_eq!(
        Connection::noxtls_build_tls13_compatibility_change_cipher_spec(),
        [0x14, 0x03, 0x03, 0x00, 0x01, 0x01]
    );
}

/// Verifies DTLS 1.3 unified records carry and authenticate negotiated Connection IDs.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn dtls13_connection_id_unified_record_round_trip_and_mismatch_reject() {
    let key = [0x11_u8; 16];
    let iv = [0x22_u8; 12];
    let cid = [0xA1_u8, 0xB2];
    let packet = noxtls_seal_dtls13_unified_aes128gcm_record_with_cid(
        1,
        7,
        &key,
        &iv,
        b"cid protected payload",
        &cid,
    )
    .expect("cid-bearing dtls13 packet should seal");

    let (header, _) = noxtls_parse_dtls13_record_header_with_cid_len(&packet, cid.len())
        .expect("cid-bearing dtls13 header should parse with negotiated cid length");
    assert_eq!(header.epoch, 1);
    assert_eq!(header.sequence, 7);
    assert_eq!(header.connection_id, cid);

    let mut replay = DtlsEpochReplayTracker::noxtls_new();
    let (opened_header, plaintext) =
        noxtls_open_dtls13_unified_aes128gcm_record_with_cid(&packet, &key, &iv, &mut replay, &cid)
            .expect("matching cid should open");
    assert_eq!(opened_header.connection_id, cid);
    assert_eq!(plaintext, b"cid protected payload");

    let mut wrong_replay = DtlsEpochReplayTracker::noxtls_new();
    assert!(noxtls_open_dtls13_unified_aes128gcm_record_with_cid(
        &packet,
        &key,
        &iv,
        &mut wrong_replay,
        &[0xA1, 0xB3],
    )
    .is_err());

    let mut no_cid_replay = DtlsEpochReplayTracker::noxtls_new();
    assert!(
        noxtls_open_dtls13_unified_aes128gcm_record(&packet, &key, &iv, &mut no_cid_replay,)
            .is_err()
    );
}

/// Verifies connection-level DTLS 1.3 application records emit and accept configured CIDs.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn dtls13_connection_ids_apply_to_application_datagrams() {
    let client_key = [0x31_u8; 16];
    let client_iv = [0x32_u8; 12];
    let server_key = [0x41_u8; 16];
    let server_iv = [0x42_u8; 12];
    let client_to_server_cid = [0xC1_u8, 0xD2, 0xE3];

    let mut client = Connection::noxtls_new(TlsVersion::Dtls13);
    client
        .noxtls_install_dtls13_traffic_keys(client_key, client_iv, server_key, server_iv)
        .expect("client dtls13 keys should install");
    client
        .noxtls_set_dtls13_outbound_connection_id(&client_to_server_cid)
        .expect("client outbound cid should configure");
    client.state = HandshakeState::Finished;

    let mut server = Connection::noxtls_new(TlsVersion::Dtls13);
    server.tls_role = TlsRole::Server;
    server
        .noxtls_install_dtls13_traffic_keys(client_key, client_iv, server_key, server_iv)
        .expect("server dtls13 keys should install");
    server
        .noxtls_set_dtls13_inbound_connection_id(&client_to_server_cid)
        .expect("server inbound cid should configure");
    server.state = HandshakeState::Finished;

    let datagrams = client
        .write_dtls13_application_data(b"cid app data", 10)
        .expect("client should write cid-bearing datagram");
    assert_eq!(datagrams.len(), 1);
    let (header, _) =
        noxtls_parse_dtls13_record_header_with_cid_len(&datagrams[0], client_to_server_cid.len())
            .expect("connection output should include cid-bearing header");
    assert_eq!(header.connection_id, client_to_server_cid);

    let plaintexts = server
        .read_dtls13_application_data(&datagrams[0], 11)
        .expect("server should read cid-bearing datagram");
    assert_eq!(plaintexts, vec![b"cid app data".to_vec()]);

    let mut wrong_server = Connection::noxtls_new(TlsVersion::Dtls13);
    wrong_server.tls_role = TlsRole::Server;
    wrong_server
        .noxtls_install_dtls13_traffic_keys(client_key, client_iv, server_key, server_iv)
        .expect("wrong server dtls13 keys should install");
    wrong_server
        .noxtls_set_dtls13_inbound_connection_id(&[0xC1, 0xD2, 0xE4])
        .expect("wrong server inbound cid should configure");
    wrong_server.state = HandshakeState::Finished;
    assert!(wrong_server
        .read_dtls13_application_data(&datagrams[0], 12)
        .is_err());
}

/// Verifies TLS 1.3 mTLS sends and verifies client Certificate + CertificateVerify end to end.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_mtls_client_certificate_roundtrip() {
    let server_private =
        P256PrivateKey::from_bytes([0x21_u8; 32]).expect("server p256 private key should parse");
    let server_public = server_private
        .public_key()
        .expect("server p256 public key should derive");
    let server_cert = noxtls_write_self_signed_certificate_p256_sha256(
        &[0x31],
        "mtls.server.test",
        "20260101000000Z",
        "20270101000000Z",
        &server_public,
        &server_private,
    )
    .expect("server certificate should encode");

    let client_private =
        P256PrivateKey::from_bytes([0x22_u8; 32]).expect("client p256 private key should parse");
    let client_public = client_private
        .public_key()
        .expect("client p256 public key should derive");
    let client_cert = noxtls_write_self_signed_certificate_p256_sha256(
        &[0x32],
        "mtls.client.test",
        "20260101000000Z",
        "20270101000000Z",
        &client_public,
        &client_private,
    )
    .expect("client certificate should encode");

    let mut client = Connection::noxtls_new(TlsVersion::Tls13);
    client.noxtls_set_tls13_client_offer_pq_key_shares(false);
    client
        .noxtls_set_tls13_client_cipher_suites(&[CipherSuite::TlsAes128GcmSha256])
        .expect("set client cipher suites");
    client.noxtls_set_tls13_require_certificate_auth(true);
    client
        .noxtls_configure_tls13_server_auth(
            core::slice::from_ref(&server_cert),
            &[],
            "20260601000000Z",
        )
        .expect("client server-auth trust should configure");
    client
        .noxtls_set_tls13_server_expected_hostname(Some("mtls.server.test"))
        .expect("server hostname policy should configure");
    client
        .noxtls_configure_tls13_client_identity(
            core::slice::from_ref(&client_cert),
            Tls13ServerIdentityKey::P256(client_private),
        )
        .expect("client identity should configure");
    let client_hello = client
        .noxtls_send_client_hello(&[0x44_u8; 32])
        .expect("client hello should build");

    let mut server = Connection::noxtls_new_tls13_server();
    server
        .noxtls_configure_tls13_server_identity(
            core::slice::from_ref(&server_cert),
            Tls13ServerIdentityKey::P256(server_private),
        )
        .expect("server identity should configure");
    server.noxtls_set_tls13_require_client_auth(true);
    server
        .noxtls_configure_tls13_client_auth(
            core::slice::from_ref(&client_cert),
            &[],
            "20260601000000Z",
        )
        .expect("server client-auth trust should configure");
    let server_hello = server
        .noxtls_accept_tls13_client_hello(&client_hello, &[0x55_u8; 32])
        .expect("server should accept client hello");

    client
        .noxtls_recv_server_hello(&server_hello)
        .expect("client should process server hello");
    server
        .noxtls_derive_handshake_secret()
        .expect("server should derive handshake secret");
    let server_flight = server
        .noxtls_build_tls13_server_handshake_flight_with_client_certificate_request(true)
        .expect("server mTLS flight should build");
    let server_flight_aad = Connection::noxtls_tls13_packet_header_aad(&server_flight)
        .expect("server flight aad should parse");
    client
        .noxtls_process_tls13_server_encrypted_handshake_flight(
            core::slice::from_ref(&server_flight),
            &server_flight_aad,
        )
        .expect("client should process requested mTLS server flight");
    assert_eq!(client.state, HandshakeState::Finished);

    let mut client_messages = Vec::new();
    for message in client
        .noxtls_prepare_tls13_client_authentication_messages()
        .expect("client auth messages should build")
    {
        client_messages.extend_from_slice(&message);
    }
    let client_finished = client
        .noxtls_prepare_tls13_client_finished_message()
        .expect("client finished should build");
    client_messages.extend_from_slice(&client_finished);

    let inner_len = client_messages
        .len()
        .checked_add(1)
        .expect("client auth inner length");
    let payload_len = inner_len
        .checked_add(16)
        .expect("client auth ciphertext length");
    let mut client_auth_aad = [0_u8; 5];
    client_auth_aad[0] = RecordContentType::ApplicationData.to_u8();
    client_auth_aad[1] = 0x03;
    client_auth_aad[2] = 0x03;
    client_auth_aad[3..5].copy_from_slice(&(payload_len as u16).to_be_bytes());
    let client_auth_packet = client
        .noxtls_seal_tls13_record_packet(
            &client_messages,
            RecordContentType::Handshake.to_u8(),
            &client_auth_aad,
            0,
        )
        .expect("client auth packet should seal");

    server
        .noxtls_recv_tls13_client_authentication_packet(&client_auth_packet)
        .expect("server should verify client certificate flight");
    assert_eq!(server.state, HandshakeState::Finished);
}

fn test_der_len(len: usize) -> Vec<u8> {
    if len < 128 {
        return vec![len as u8];
    }
    if len <= 0xff {
        return vec![0x81, len as u8];
    }
    vec![0x82, ((len >> 8) & 0xff) as u8, (len & 0xff) as u8]
}

fn test_der(tag: u8, body: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    out.push(tag);
    out.extend_from_slice(&test_der_len(body.len()));
    out.extend_from_slice(body);
    out
}

fn test_der_sequence(parts: &[Vec<u8>]) -> Vec<u8> {
    let mut body = Vec::new();
    for part in parts {
        body.extend_from_slice(part);
    }
    test_der(0x30, &body)
}

fn test_ocsp_response(
    status_tag: u8,
    produced_at: &str,
    this_update: &str,
    next_update: &str,
) -> Vec<u8> {
    let cert_id = test_der_sequence(&[]);
    let cert_status = test_der(status_tag, &[]);
    let this_update = test_der(0x18, this_update.as_bytes());
    let next_update = test_der(0xA0, &test_der(0x18, next_update.as_bytes()));
    let single_response = test_der_sequence(&[cert_id, cert_status, this_update, next_update]);
    let responses = test_der_sequence(&[single_response]);
    let responder_id = test_der(0xA1, &test_der(0x04, b"responder"));
    let produced_at = test_der(0x18, produced_at.as_bytes());
    let response_data = test_der_sequence(&[responder_id, produced_at, responses]);
    let signature_algorithm = test_der_sequence(&[]);
    let signature = test_der(0x03, &[0x00]);
    let basic_response = test_der_sequence(&[response_data, signature_algorithm, signature]);
    let response_type = test_der(
        0x06,
        &[0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x01],
    );
    let response_octets = test_der(0x04, &basic_response);
    let response_bytes = test_der_sequence(&[response_type, response_octets]);
    test_der_sequence(&[test_der(0x0A, &[0x00]), test_der(0xA0, &response_bytes)])
}

/// Verifies built-in TLS 1.3 OCSP staple parsing classifies freshness and revocation.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_ocsp_staple_builtin_parser_classifies_status() {
    let good = test_ocsp_response(
        0x80,
        "20260501000000Z",
        "20260501000000Z",
        "20260601000000Z",
    );
    let info = noxtls_parse_tls13_ocsp_staple_info(&good, "20260515000000Z")
        .expect("fresh good ocsp staple should parse");
    assert_eq!(info.status, Tls13OcspStapleVerification::Good);
    assert_eq!(info.produced_at, "20260501000000Z");
    assert_eq!(info.this_update, "20260501000000Z");
    assert_eq!(info.next_update.as_deref(), Some("20260601000000Z"));
    assert_eq!(
        noxtls_verify_tls13_ocsp_staple(&good, "20260515000000Z")
            .expect("fresh good ocsp staple should verify"),
        Tls13OcspStapleVerification::Good
    );

    let expired = test_ocsp_response(
        0x80,
        "20260501000000Z",
        "20260501000000Z",
        "20260510000000Z",
    );
    assert_eq!(
        noxtls_verify_tls13_ocsp_staple(&expired, "20260515000000Z")
            .expect("expired ocsp staple should classify"),
        Tls13OcspStapleVerification::Expired
    );

    let revoked = test_ocsp_response(
        0xA1,
        "20260501000000Z",
        "20260501000000Z",
        "20260601000000Z",
    );
    assert_eq!(
        noxtls_verify_tls13_ocsp_staple(&revoked, "20260515000000Z")
            .expect("revoked ocsp staple should classify"),
        Tls13OcspStapleVerification::Revoked
    );
}

/// Verifies TLS 1.3 Certificate processing performs built-in OCSP freshness validation.
///
/// # Panics
///
/// This function does not panic.
#[test]
fn tls13_certificate_processing_validates_ocsp_staple_without_custom_hook() {
    let private_key =
        P256PrivateKey::from_bytes([0x51_u8; 32]).expect("p256 private key fixture should parse");
    let public_key = private_key.public_key().expect("p256 public key");
    let cert_der = noxtls_write_self_signed_certificate_p256_sha256(
        &[0x51],
        "ocsp.example.test",
        "20260101000000Z",
        "20270101000000Z",
        &public_key,
        &private_key,
    )
    .expect("self-signed certificate should build");
    let good_ocsp = test_ocsp_response(
        0x80,
        "20260501000000Z",
        "20260501000000Z",
        "20260601000000Z",
    );
    let certificate =
        Connection::noxtls_build_certificate_message_with_ocsp_staple(&cert_der, Some(&good_ocsp))
            .expect("certificate with ocsp staple should build");

    let mut client = Connection::noxtls_new(TlsVersion::Tls13);
    client.state = HandshakeState::ServerEncryptedExtensionsReceived;
    client.noxtls_set_tls13_require_certificate_auth(true);
    client.noxtls_set_tls13_require_ocsp_staple(true);
    client
        .noxtls_configure_tls13_server_auth(
            core::slice::from_ref(&cert_der),
            &[],
            "20260515000000Z",
        )
        .expect("server auth policy should configure");
    client
        .noxtls_set_tls13_server_expected_hostname(Some("ocsp.example.test"))
        .expect("hostname should configure");
    client
        .noxtls_recv_certificate(&certificate)
        .expect("fresh ocsp staple should be accepted");
    assert!(client.noxtls_tls13_server_ocsp_staple_verified());
    assert_eq!(
        client.noxtls_tls13_server_ocsp_staple(),
        Some(good_ocsp.as_slice())
    );

    let expired_ocsp = test_ocsp_response(
        0x80,
        "20260501000000Z",
        "20260501000000Z",
        "20260510000000Z",
    );
    let expired_certificate = Connection::noxtls_build_certificate_message_with_ocsp_staple(
        &cert_der,
        Some(&expired_ocsp),
    )
    .expect("certificate with expired ocsp staple should build");
    let mut expired_client = Connection::noxtls_new(TlsVersion::Tls13);
    expired_client.state = HandshakeState::ServerEncryptedExtensionsReceived;
    expired_client.noxtls_set_tls13_require_certificate_auth(true);
    expired_client.noxtls_set_tls13_require_ocsp_staple(true);
    expired_client
        .noxtls_configure_tls13_server_auth(&[cert_der], &[], "20260515000000Z")
        .expect("server auth policy should configure");
    expired_client
        .noxtls_set_tls13_server_expected_hostname(Some("ocsp.example.test"))
        .expect("hostname should configure");
    assert!(expired_client
        .noxtls_recv_certificate(&expired_certificate)
        .is_err());
}