rustls 0.24.0-dev.1

Rustls is a modern TLS library written in Rust.
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
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::ops::{Deref, DerefMut};
use core::{fmt, mem};

use pki_types::{DnsName, FipsStatus, ServerName};

use crate::TlsInputBuffer;
use crate::client::{ClientConfig, ClientSide};
pub use crate::common_state::Side;
use crate::common_state::{CommonState, ConnectionOutputs, Protocol};
use crate::conn::{ConnectionCore, KeyingMaterialExporter, MessageIter, SideData, StateMachine};
use crate::crypto::cipher::{AeadKey, Iv, Payload};
use crate::crypto::tls13::{Hkdf, HkdfExpander, OkmBlock};
use crate::enums::ApplicationProtocol;
use crate::error::{ApiMisuse, Error};
use crate::msgs::{
    ClientExtensionsInput, Message, MessagePayload, ServerExtensionsInput, TransportParameters,
};
use crate::server::{ChooseConfig, ClientHello, ServerConfig, ServerSide, ServerState};
use crate::suites::SupportedCipherSuite;
use crate::sync::Arc;
use crate::tls13::Tls13CipherSuite;
use crate::tls13::key_schedule::{
    hkdf_expand_label, hkdf_expand_label_aead_key, hkdf_expand_label_block,
};

/// A QUIC client or server connection.
pub trait Connection: fmt::Debug + Deref<Target = ConnectionOutputs> {
    /// Return the TLS-encoded transport parameters for the session's peer.
    ///
    /// While the transport parameters are technically available prior to the
    /// completion of the handshake, they cannot be fully trusted until the
    /// handshake completes, and reliance on them should be minimized.
    /// However, any tampering with the parameters will cause the handshake
    /// to fail.
    fn quic_transport_parameters(&self) -> Option<&[u8]>;

    /// Compute the keys for encrypting/decrypting 0-RTT packets, if available
    fn zero_rtt_keys(&self) -> Option<DirectionalKeys>;

    /// Consume unencrypted TLS handshake data.
    ///
    /// Handshake data obtained from separate encryption levels should be supplied in separate calls.
    ///
    /// How much of the `input` buffer is consumed is recorded by a call to
    /// [`TlsInputBuffer::discard()`].  Unconsumed data should be presented again on the next call.
    fn read_hs(&mut self, input: &mut dyn TlsInputBuffer) -> Result<(), Error>;

    /// Obtain pending events that the caller should process.
    ///
    /// All pending events are returned as an iterator.
    fn events(&mut self) -> impl Iterator<Item = QuicEvent>;

    /// Returns true if the connection is currently performing the TLS handshake.
    fn is_handshaking(&self) -> bool;
}

/// A QUIC client connection.
pub struct ClientConnection {
    inner: ConnectionCommon<ClientSide>,
}

impl ClientConnection {
    /// Make a new QUIC ClientConnection.
    ///
    /// This differs from `ClientConnection::new()` in that it takes an extra `params` argument,
    /// which contains the TLS-encoded transport parameters to send.
    pub fn new(
        config: Arc<ClientConfig>,
        quic_version: Version,
        name: ServerName<'static>,
        params: Vec<u8>,
    ) -> Result<Self, Error> {
        let alpn_protocols = config.alpn_protocols.clone();
        Self::new_with_alpn(config, quic_version, name, params, alpn_protocols)
    }

    /// Make a new QUIC ClientConnection with custom ALPN protocols.
    pub fn new_with_alpn(
        config: Arc<ClientConfig>,
        version: Version,
        name: ServerName<'static>,
        params: Vec<u8>,
        alpn_protocols: Vec<ApplicationProtocol<'static>>,
    ) -> Result<Self, Error> {
        let suites = &config.provider().tls13_cipher_suites;
        if suites.is_empty() {
            return Err(ApiMisuse::QuicRequiresTls13Support.into());
        }

        if !suites
            .iter()
            .any(|scs| scs.quic.is_some())
        {
            return Err(ApiMisuse::NoQuicCompatibleCipherSuites.into());
        }

        let exts = ClientExtensionsInput {
            transport_parameters: Some(match version {
                Version::V1 | Version::V2 => TransportParameters::Quic(Payload::new(params)),
            }),

            ..ClientExtensionsInput::from_alpn(alpn_protocols)
        };

        let mut quic = Quic {
            version,
            ..Quic::default()
        };

        let inner = ConnectionCore::for_client(
            config,
            name,
            exts,
            Some(&mut quic),
            Protocol::Quic(version),
        )?;

        Ok(Self {
            inner: ConnectionCommon::new(inner, quic),
        })
    }

    /// Return the FIPS validation status of the connection.
    pub fn fips(&self) -> FipsStatus {
        self.inner.fips
    }

    /// Returns True if the server signalled it will process early data.
    ///
    /// If you sent early data and this returns false at the end of the
    /// handshake then the server will not process the data.  This
    /// is not an error, but you may wish to resend the data.
    pub fn is_early_data_accepted(&self) -> bool {
        self.inner.core.is_early_data_accepted()
    }

    /// Returns the number of TLS1.3 tickets that have been received.
    pub fn tls13_tickets_received(&self) -> u32 {
        self.inner
            .core
            .common
            .recv
            .tls13_tickets_received
    }

    /// Returns an object that can derive key material from the agreed connection secrets.
    ///
    /// See [RFC5705][] for more details on what this is for.
    ///
    /// This function can be called at most once per connection.
    ///
    /// This function will error:
    ///
    /// - if called prior to the handshake completing; (check with
    ///   [`CommonState::is_handshaking`] first).
    /// - if called more than once per connection.
    ///
    /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
    pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
        self.inner.core.exporter()
    }
}

impl Connection for ClientConnection {
    fn quic_transport_parameters(&self) -> Option<&[u8]> {
        self.inner.quic_transport_parameters()
    }

    fn zero_rtt_keys(&self) -> Option<DirectionalKeys> {
        self.inner.zero_rtt_keys()
    }

    fn read_hs(&mut self, input: &mut dyn TlsInputBuffer) -> Result<(), Error> {
        self.inner.read_hs(input)
    }

    fn events(&mut self) -> impl Iterator<Item = QuicEvent> {
        self.inner.events()
    }

    fn is_handshaking(&self) -> bool {
        self.inner.is_handshaking()
    }
}

impl Deref for ClientConnection {
    type Target = ConnectionOutputs;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl fmt::Debug for ClientConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("quic::ClientConnection")
            .finish_non_exhaustive()
    }
}

/// A QUIC server connection.
pub struct ServerConnection {
    inner: ConnectionCommon<ServerSide>,
}

impl ServerConnection {
    /// Make a new QUIC ServerConnection.
    ///
    /// This differs from `ServerConnection::new()` in that it takes an extra `params` argument,
    /// which contains the TLS-encoded transport parameters to send.
    pub fn new(
        config: Arc<ServerConfig>,
        version: Version,
        params: Vec<u8>,
    ) -> Result<Self, Error> {
        check_server_config(&config)?;
        let exts = ServerExtensionsInput {
            transport_parameters: Some(match version {
                Version::V1 | Version::V2 => TransportParameters::Quic(Payload::new(params)),
            }),
        };

        let core = ConnectionCore::for_server(config, exts, Protocol::Quic(version))?;
        let inner = ConnectionCommon::new(
            core,
            Quic {
                version,
                ..Quic::default()
            },
        );
        Ok(Self { inner })
    }

    /// Return the FIPS validation status of the connection.
    pub fn fips(&self) -> FipsStatus {
        self.inner.fips
    }

    /// Retrieves the server name, if any, used to select the certificate and
    /// private key.
    ///
    /// This returns `None` until some time after the client's server name indication
    /// (SNI) extension value is processed during the handshake. It will never be
    /// `None` when the connection is ready to send or process application data,
    /// unless the client does not support SNI.
    ///
    /// This is useful for application protocols that need to enforce that the
    /// server name matches an application layer protocol hostname. For
    /// example, HTTP/1.1 servers commonly expect the `Host:` header field of
    /// every request on a connection to match the hostname in the SNI extension
    /// when the client provides the SNI extension.
    ///
    /// The server name is also used to match sessions during session resumption.
    pub fn server_name(&self) -> Option<&DnsName<'_>> {
        self.inner.core.side.server_name()
    }

    /// Set the resumption data to embed in future resumption tickets supplied to the client.
    ///
    /// Defaults to the empty byte string. Must be less than 2^15 bytes to allow room for other
    /// data. Should be called while `is_handshaking` returns true to ensure all transmitted
    /// resumption tickets are affected (otherwise an error will be returned).
    ///
    /// Integrity will be assured by rustls, but the data will be visible to the client. If secrecy
    /// from the client is desired, encrypt the data separately.
    pub fn set_resumption_data(&mut self, resumption_data: &[u8]) -> Result<(), Error> {
        assert!(resumption_data.len() < 2usize.pow(15));
        match &mut self.inner.core.state {
            Ok(st) => st.set_resumption_data(resumption_data),
            Err(e) => Err(e.clone()),
        }
    }

    /// Retrieves the resumption data supplied by the client, if any.
    ///
    /// Returns `Some` if and only if a valid resumption ticket has been received from the client.
    pub fn received_resumption_data(&self) -> Option<&[u8]> {
        self.inner
            .core
            .side
            .received_resumption_data()
    }

    /// Returns an object that can derive key material from the agreed connection secrets.
    ///
    /// See [RFC5705][] for more details on what this is for.
    ///
    /// This function can be called at most once per connection.
    ///
    /// This function will error:
    ///
    /// - if called prior to the handshake completing; (check with
    ///   [`CommonState::is_handshaking`] first).
    /// - if called more than once per connection.
    ///
    /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
    pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
        self.inner.core.exporter()
    }
}

impl Connection for ServerConnection {
    fn quic_transport_parameters(&self) -> Option<&[u8]> {
        self.inner.quic_transport_parameters()
    }

    fn zero_rtt_keys(&self) -> Option<DirectionalKeys> {
        self.inner.zero_rtt_keys()
    }

    fn read_hs(&mut self, input: &mut dyn TlsInputBuffer) -> Result<(), Error> {
        self.inner.read_hs(input)
    }

    fn events(&mut self) -> impl Iterator<Item = QuicEvent> {
        self.inner.events()
    }

    fn is_handshaking(&self) -> bool {
        self.inner.is_handshaking()
    }
}

impl Deref for ServerConnection {
    type Target = ConnectionOutputs;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl fmt::Debug for ServerConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("quic::ServerConnection")
            .finish_non_exhaustive()
    }
}

/// An in-progress TLS server handshake.
#[non_exhaustive]
#[derive(Debug)]
pub enum ServerHandshake {
    /// More data needs to be received to make progress.
    NeedsInput(NeedsInput),

    /// A complete `ClientHello` has been received.
    ///
    /// The handshake can be progressed by choosing a [`ServerConfig`] based on
    /// [`Accepted::client_hello()`] and providing it to [`Accepted::choose_config()`].
    Accepted(Accepted),

    /// The handshake is complete.
    Complete(ServerConnection),
}

impl ServerHandshake {
    /// Creates a new QUIC [`ServerHandshake`] via the payload of the [`ServerHandshake::NeedsInput`] variant.
    ///
    /// It is a fundamental fact of server TLS connections that the server reads first; this is reflected
    /// in the returned type.
    ///
    /// You may wrap this in the [`ServerHandshake::NeedsInput`] variant to generalise the type to a
    /// [`ServerHandshake`].
    ///
    /// The returned object should be fed data from a single potential client.
    pub fn start(version: Version) -> NeedsInput {
        NeedsInput {
            inner: ConnectionCommon::new(
                ConnectionCore::for_acceptor(Protocol::Quic(version)),
                Quic {
                    version,
                    ..Quic::default()
                },
            ),
        }
    }
}

impl TryFrom<ConnectionCommon<ServerSide>> for ServerHandshake {
    type Error = Error;

    fn try_from(mut inner: ConnectionCommon<ServerSide>) -> Result<Self, Error> {
        const MISUSED: Error = Error::Unreachable("forgot to restore state");

        Ok(match mem::replace(&mut inner.core.state, Err(MISUSED))? {
            ServerState::ChooseConfig(choose_config) => Self::Accepted(Accepted {
                inner,
                choose_config,
            }),

            state if state.is_traffic() => {
                inner.core.state = Ok(state);
                Self::Complete(ServerConnection { inner })
            }

            state => {
                inner.core.state = Ok(state);
                Self::NeedsInput(NeedsInput { inner })
            }
        })
    }
}

/// More data needs to be received to make progress.
///
/// Provide the data to [`Self::process()`].
pub struct NeedsInput {
    inner: ConnectionCommon<ServerSide>,
}

impl NeedsInput {
    /// Progress the handshake by receiving further unencrypted TLS handshake data.
    ///
    /// The input should be ordered QUIC CRYPTO stream data for one encryption level.
    ///
    /// Handshake data obtained from separate encryption levels should be supplied in separate calls.
    ///
    /// How much of the `input` buffer is consumed is recorded by a call to
    /// [`TlsInputBuffer::discard()`].  Unconsumed data should be presented again on the next call.
    ///
    /// An error from this function is fatal to the connection, as it consumes the [`NeedsInput`]
    /// object.
    ///
    /// On success, this returns:
    ///
    /// - a [`ServerHandshake::NeedsInput`] if more data is required.
    /// - a [`ServerHandshake::Accepted`] if a whole `ClientHello` has been received,
    ///   and a choice of [`ServerConfig`] is required to continue.
    /// - a [`ServerHandshake::Complete`] if the handshake is complete.
    ///
    /// `output` has any resulting handshake messages or key changes appended to it.
    pub fn process(
        mut self,
        input: &mut dyn TlsInputBuffer,
        output: &mut Vec<QuicEvent>,
    ) -> Result<ServerHandshake, Error> {
        self.inner.read_hs(input)?;
        output.extend(self.inner.events());
        ServerHandshake::try_from(self.inner)
    }
}

impl fmt::Debug for NeedsInput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("quic::NeedsInput")
            .finish_non_exhaustive()
    }
}

/// Represents that a `ClientHello` message has been received.
///
/// The handshake can be progressed by choosing a [`ServerConfig`] based on
/// [`Accepted::client_hello()`] and providing it to [`Accepted::choose_config()`].
pub struct Accepted {
    // invariant: `inner.core.state` is `Err(_)` and requires restoring
    inner: ConnectionCommon<ServerSide>,
    choose_config: Box<ChooseConfig>,
}

impl Accepted {
    /// Get the [`ClientHello`] for this connection.
    pub fn client_hello(&self) -> ClientHello<'_> {
        self.choose_config.client_hello()
    }

    /// Choose a [`ServerConfig`] to progress the handshake.
    ///
    /// Resolves an [`Accepted`], providing the [`ServerConfig`] that should be used for
    /// the session, and the TLS-encoded QUIC transport parameters to send.
    ///
    /// Returns an error if configuration-dependent validation of the received
    /// `ClientHello` message fails.
    ///
    /// Events are appended to `output`.
    pub fn choose_config(
        mut self,
        config: Arc<ServerConfig>,
        params: Vec<u8>,
        output: &mut Vec<QuicEvent>,
    ) -> Result<ServerHandshake, Error> {
        check_server_config(&config)?;

        self.inner.core.accepted(
            self.choose_config,
            ServerExtensionsInput {
                transport_parameters: Some(match self.inner.quic.version {
                    Version::V1 | Version::V2 => TransportParameters::Quic(Payload::new(params)),
                }),
            },
            Some(&mut self.inner.quic),
            config,
        )?;

        output.extend(self.inner.events());

        ServerHandshake::try_from(self.inner)
    }
}

impl fmt::Debug for Accepted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("quic::Accepted")
            .finish_non_exhaustive()
    }
}

fn check_server_config(config: &ServerConfig) -> Result<(), Error> {
    let suites = &config.provider.tls13_cipher_suites;
    if suites.is_empty() {
        return Err(ApiMisuse::QuicRequiresTls13Support.into());
    }

    if !suites
        .iter()
        .any(|scs| scs.quic.is_some())
    {
        return Err(ApiMisuse::NoQuicCompatibleCipherSuites.into());
    }

    if config.max_early_data_size != 0 && config.max_early_data_size != 0xffff_ffff {
        return Err(ApiMisuse::QuicRestrictsMaxEarlyDataSize.into());
    }

    Ok(())
}

/// QUIC events that should be handled by the caller.
#[expect(clippy::large_enum_variant)]
#[derive(Debug)]
#[non_exhaustive]
pub enum QuicEvent {
    /// These bytes should be handled as an unencrypted TLS handshake message.
    Message(Vec<u8>),

    /// The key material should be changed.
    KeyChange(KeyChange),
}

/// A shared interface for QUIC connections.
struct ConnectionCommon<Side: SideData> {
    core: ConnectionCore<Side>,
    quic: Quic,
}

impl<Side: SideData> ConnectionCommon<Side> {
    fn new(core: ConnectionCore<Side>, quic: Quic) -> Self {
        Self { core, quic }
    }

    fn quic_transport_parameters(&self) -> Option<&[u8]> {
        self.quic
            .params
            .as_ref()
            .map(|v| v.as_ref())
    }

    fn zero_rtt_keys(&self) -> Option<DirectionalKeys> {
        let suite = self
            .core
            .common
            .negotiated_cipher_suite()
            .and_then(|suite| match suite {
                SupportedCipherSuite::Tls13(suite) => Some(suite),
                _ => None,
            })?;

        Some(DirectionalKeys::new(
            suite,
            suite.quic?,
            self.quic.early_secret.as_ref()?,
            self.quic.version,
        ))
    }

    fn read_hs(&mut self, input: &mut dyn TlsInputBuffer) -> Result<(), Error> {
        self.core
            .common
            .recv
            .deframer
            .input_quic(input.slice_mut())?;

        let mut iter = MessageIter::new(input, Some(&mut self.quic), &mut self.core);
        let result = match iter.next() {
            Some(Ok(_)) | None => Ok(()),
            Some(Err(e)) => Err(e),
        };

        input.discard(
            self.core
                .common
                .recv
                .deframer
                .take_discard(),
        );

        result
    }

    fn events(&mut self) -> impl Iterator<Item = QuicEvent> {
        self.quic.events()
    }
}

impl<Side: SideData> Deref for ConnectionCommon<Side> {
    type Target = CommonState;

    fn deref(&self) -> &Self::Target {
        &self.core.common
    }
}

impl<Side: SideData> DerefMut for ConnectionCommon<Side> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.core.common
    }
}

#[derive(Default)]
pub(crate) struct Quic {
    pub(crate) version: Version,
    /// QUIC transport parameters received from the peer during the handshake
    pub(crate) params: Option<Vec<u8>>,
    pub(crate) events: Vec<QuicEvent>,
    pub(crate) early_secret: Option<OkmBlock>,
}

impl Quic {
    pub(crate) fn send_msg(&mut self, m: Message<'_>, _must_encrypt: bool) {
        if let MessagePayload::Alert(_) = m.payload {
            // alerts are sent out-of-band in QUIC mode
            return;
        }

        debug_assert!(
            matches!(
                m.payload,
                MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
            ),
            "QUIC uses TLS for the cryptographic handshake only"
        );
        let mut bytes = Vec::new();
        m.payload.encode(&mut bytes);
        self.events
            .push(QuicEvent::Message(bytes));
    }

    pub(crate) fn events(&mut self) -> impl Iterator<Item = QuicEvent> {
        mem::take(&mut self.events).into_iter()
    }
}

impl QuicOutput for Quic {
    fn transport_parameters(&mut self, params: Vec<u8>) {
        self.params = Some(params);
    }

    fn early_secret(&mut self, secret: Option<OkmBlock>) {
        self.early_secret = secret;
    }

    fn handshake_secrets(
        &mut self,
        client_secret: OkmBlock,
        server_secret: OkmBlock,
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        side: Side,
    ) {
        self.events
            .push(QuicEvent::KeyChange(KeyChange::Handshake {
                keys: Keys::new(&Secrets::new(
                    client_secret,
                    server_secret,
                    suite,
                    quic,
                    side,
                    self.version,
                )),
            }));
    }

    fn traffic_secrets(
        &mut self,
        client_secret: OkmBlock,
        server_secret: OkmBlock,
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        side: Side,
    ) {
        let mut secrets = Secrets::new(
            client_secret,
            server_secret,
            suite,
            quic,
            side,
            self.version,
        );
        let keys = Keys::new(&secrets);
        secrets.update();
        self.events
            .push(QuicEvent::KeyChange(KeyChange::OneRtt {
                keys,
                next: secrets,
            }));
    }

    fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
        self.send_msg(m, must_encrypt);
    }
}

pub(crate) trait QuicOutput {
    fn transport_parameters(&mut self, params: Vec<u8>);

    fn early_secret(&mut self, secret: Option<OkmBlock>);

    fn handshake_secrets(
        &mut self,
        client_secret: OkmBlock,
        server_secret: OkmBlock,
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        side: Side,
    );

    fn traffic_secrets(
        &mut self,
        client_secret: OkmBlock,
        server_secret: OkmBlock,
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        side: Side,
    );

    fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool);
}

/// Secrets used to encrypt/decrypt traffic
#[derive(Clone)]
pub struct Secrets {
    /// Secret used to encrypt packets transmitted by the client
    pub(crate) client: OkmBlock,
    /// Secret used to encrypt packets transmitted by the server
    pub(crate) server: OkmBlock,
    /// Cipher suite used with these secrets
    suite: &'static Tls13CipherSuite,
    quic: &'static dyn Algorithm,
    side: Side,
    version: Version,
}

impl Secrets {
    pub(crate) fn new(
        client: OkmBlock,
        server: OkmBlock,
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        side: Side,
        version: Version,
    ) -> Self {
        Self {
            client,
            server,
            suite,
            quic,
            side,
            version,
        }
    }

    /// Derive the next set of packet keys
    pub fn next_packet_keys(&mut self) -> PacketKeySet {
        let keys = PacketKeySet::new(self);
        self.update();
        keys
    }

    pub(crate) fn update(&mut self) {
        self.client = hkdf_expand_label_block(
            self.suite
                .hkdf_provider
                .expander_for_okm(&self.client)
                .as_ref(),
            self.version.key_update_label(),
            &[],
        );
        self.server = hkdf_expand_label_block(
            self.suite
                .hkdf_provider
                .expander_for_okm(&self.server)
                .as_ref(),
            self.version.key_update_label(),
            &[],
        );
    }

    fn local_remote(&self) -> (&OkmBlock, &OkmBlock) {
        match self.side {
            Side::Client => (&self.client, &self.server),
            Side::Server => (&self.server, &self.client),
        }
    }
}

/// Keys used to communicate in a single direction
#[expect(clippy::exhaustive_structs)]
pub struct DirectionalKeys {
    /// Encrypts or decrypts a packet's headers
    pub header: Box<dyn HeaderProtectionKey>,
    /// Encrypts or decrypts the payload of a packet
    pub packet: Box<dyn PacketKey>,
}

impl DirectionalKeys {
    pub(crate) fn new(
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        secret: &OkmBlock,
        version: Version,
    ) -> Self {
        let builder = KeyBuilder::new(secret, version, quic, suite.hkdf_provider);
        Self {
            header: builder.header_protection_key(),
            packet: builder.packet_key(),
        }
    }
}

/// All AEADs we support have 16-byte tags.
const TAG_LEN: usize = 16;

/// Authentication tag from an AEAD seal operation.
pub struct Tag([u8; TAG_LEN]);

impl From<&[u8]> for Tag {
    fn from(value: &[u8]) -> Self {
        let mut array = [0u8; TAG_LEN];
        array.copy_from_slice(value);
        Self(array)
    }
}

impl AsRef<[u8]> for Tag {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// How a `Tls13CipherSuite` generates `PacketKey`s and `HeaderProtectionKey`s.
pub trait Algorithm: Send + Sync {
    /// Produce a `PacketKey` encrypter/decrypter for this suite.
    ///
    /// `suite` is the entire suite this `Algorithm` appeared in.
    /// `key` and `iv` is the key material to use.
    fn packet_key(&self, key: AeadKey, iv: Iv) -> Box<dyn PacketKey>;

    /// Produce a `HeaderProtectionKey` encrypter/decrypter for this suite.
    ///
    /// `key` is the key material, which is `aead_key_len()` bytes in length.
    fn header_protection_key(&self, key: AeadKey) -> Box<dyn HeaderProtectionKey>;

    /// The length in bytes of keys for this Algorithm.
    ///
    /// This controls the size of `AeadKey`s presented to `packet_key()` and `header_protection_key()`.
    fn aead_key_len(&self) -> usize;

    /// Whether this algorithm is FIPS-approved.
    fn fips(&self) -> FipsStatus {
        FipsStatus::Unvalidated
    }
}

/// A QUIC header protection key
pub trait HeaderProtectionKey: Send + Sync {
    /// Adds QUIC Header Protection.
    ///
    /// `sample` must contain the sample of encrypted payload; see
    /// [Header Protection Sample].
    ///
    /// `first` must reference the first byte of the header, referred to as
    /// `packet[0]` in [Header Protection Application].
    ///
    /// `packet_number` must reference the Packet Number field; this is
    /// `packet[pn_offset:pn_offset+pn_length]` in [Header Protection Application].
    ///
    /// Returns an error without modifying anything if `sample` is not
    /// the correct length (see [Header Protection Sample] and [`Self::sample_len()`]),
    /// or `packet_number` is longer than allowed (see [Packet Number Encoding and Decoding]).
    ///
    /// Otherwise, `first` and `packet_number` will have the header protection added.
    ///
    /// [Header Protection Application]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.1
    /// [Header Protection Sample]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.2
    /// [Packet Number Encoding and Decoding]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.1
    fn encrypt_in_place(
        &self,
        sample: &[u8],
        first: &mut u8,
        packet_number: &mut [u8],
    ) -> Result<(), Error>;

    /// Removes QUIC Header Protection.
    ///
    /// `sample` must contain the sample of encrypted payload; see
    /// [Header Protection Sample].
    ///
    /// `first` must reference the first byte of the header, referred to as
    /// `packet[0]` in [Header Protection Application].
    ///
    /// `packet_number` must reference the Packet Number field; this is
    /// `packet[pn_offset:pn_offset+pn_length]` in [Header Protection Application].
    ///
    /// Returns an error without modifying anything if `sample` is not
    /// the correct length (see [Header Protection Sample] and [`Self::sample_len()`]),
    /// or `packet_number` is longer than allowed (see
    /// [Packet Number Encoding and Decoding]).
    ///
    /// Otherwise, `first` and `packet_number` will have the header protection removed.
    ///
    /// [Header Protection Application]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.1
    /// [Header Protection Sample]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.2
    /// [Packet Number Encoding and Decoding]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.1
    fn decrypt_in_place(
        &self,
        sample: &[u8],
        first: &mut u8,
        packet_number: &mut [u8],
    ) -> Result<(), Error>;

    /// Expected sample length for the key's algorithm
    fn sample_len(&self) -> usize;
}

/// Keys to encrypt or decrypt the payload of a packet
pub trait PacketKey: Send + Sync {
    /// Encrypt a QUIC packet
    ///
    /// Takes a `packet_number` and optional `path_id`, used to derive the nonce; the packet
    /// `header`, which is used as the additional authenticated data; and the `payload`. The
    /// authentication tag is returned if encryption succeeds.
    ///
    /// Fails if and only if the payload is longer than allowed by the cipher suite's AEAD algorithm.
    ///
    /// When provided, the `path_id` is used for multipath encryption as described in
    /// <https://www.ietf.org/archive/id/draft-ietf-quic-multipath-15.html#section-2.4>.
    fn encrypt_in_place(
        &self,
        packet_number: u64,
        header: &[u8],
        payload: &mut [u8],
        path_id: Option<u32>,
    ) -> Result<Tag, Error>;

    /// Decrypt a QUIC packet
    ///
    /// Takes a `packet_number` and optional `path_id`, used to derive the nonce; the packet
    /// `header`, which is used as the additional authenticated data, and the `payload`, which
    /// includes the authentication tag.
    ///
    /// On success, returns the slice of `payload` containing the decrypted data.
    ///
    /// When provided, the `path_id` is used for multipath encryption as described in
    /// <https://www.ietf.org/archive/id/draft-ietf-quic-multipath-15.html#section-2.4>.
    fn decrypt_in_place<'a>(
        &self,
        packet_number: u64,
        header: &[u8],
        payload: &'a mut [u8],
        path_id: Option<u32>,
    ) -> Result<&'a [u8], Error>;

    /// Tag length for the underlying AEAD algorithm
    fn tag_len(&self) -> usize;

    /// Number of QUIC messages that can be safely encrypted with a single key of this type.
    ///
    /// Once a `MessageEncrypter` produced for this suite has encrypted more than
    /// `confidentiality_limit` messages, an attacker gains an advantage in distinguishing it
    /// from an ideal pseudorandom permutation (PRP).
    ///
    /// This is to be set on the assumption that messages are maximally sized --
    /// 2 ** 16. For non-QUIC TCP connections see [`CipherSuiteCommon::confidentiality_limit`][csc-limit].
    ///
    /// [csc-limit]: crate::crypto::CipherSuiteCommon::confidentiality_limit
    fn confidentiality_limit(&self) -> u64;

    /// Number of QUIC messages that can be safely decrypted with a single key of this type
    ///
    /// Once a `MessageDecrypter` produced for this suite has failed to decrypt `integrity_limit`
    /// messages, an attacker gains an advantage in forging messages.
    ///
    /// This is not relevant for TLS over TCP (which is also implemented in this crate)
    /// because a single failed decryption is fatal to the connection.
    /// However, this quantity is used by QUIC.
    fn integrity_limit(&self) -> u64;
}

/// Packet protection keys for bidirectional 1-RTT communication
#[expect(clippy::exhaustive_structs)]
pub struct PacketKeySet {
    /// Encrypts outgoing packets
    pub local: Box<dyn PacketKey>,
    /// Decrypts incoming packets
    pub remote: Box<dyn PacketKey>,
}

impl PacketKeySet {
    fn new(secrets: &Secrets) -> Self {
        let (local, remote) = secrets.local_remote();
        let (version, alg, hkdf) = (secrets.version, secrets.quic, secrets.suite.hkdf_provider);
        Self {
            local: KeyBuilder::new(local, version, alg, hkdf).packet_key(),
            remote: KeyBuilder::new(remote, version, alg, hkdf).packet_key(),
        }
    }
}

/// Helper for building QUIC packet and header protection keys
pub struct KeyBuilder<'a> {
    expander: Box<dyn HkdfExpander>,
    version: Version,
    alg: &'a dyn Algorithm,
}

impl<'a> KeyBuilder<'a> {
    /// Create a new KeyBuilder
    pub fn new(
        secret: &OkmBlock,
        version: Version,
        alg: &'a dyn Algorithm,
        hkdf: &'a dyn Hkdf,
    ) -> Self {
        Self {
            expander: hkdf.expander_for_okm(secret),
            version,
            alg,
        }
    }

    /// Derive packet keys
    pub fn packet_key(&self) -> Box<dyn PacketKey> {
        let aead_key_len = self.alg.aead_key_len();
        let packet_key = hkdf_expand_label_aead_key(
            self.expander.as_ref(),
            aead_key_len,
            self.version.packet_key_label(),
            &[],
        );

        let packet_iv =
            hkdf_expand_label(self.expander.as_ref(), self.version.packet_iv_label(), &[]);
        self.alg
            .packet_key(packet_key, packet_iv)
    }

    /// Derive header protection keys
    pub fn header_protection_key(&self) -> Box<dyn HeaderProtectionKey> {
        let header_key = hkdf_expand_label_aead_key(
            self.expander.as_ref(),
            self.alg.aead_key_len(),
            self.version.header_key_label(),
            &[],
        );
        self.alg
            .header_protection_key(header_key)
    }
}

/// Produces QUIC initial keys from a TLS 1.3 ciphersuite and a QUIC key generation algorithm.
#[non_exhaustive]
#[derive(Clone, Copy)]
pub struct Suite {
    /// The TLS 1.3 ciphersuite used to derive keys.
    pub suite: &'static Tls13CipherSuite,
    /// The QUIC key generation algorithm used to derive keys.
    pub quic: &'static dyn Algorithm,
}

impl Suite {
    /// Produce a set of initial keys given the connection ID, side and version
    pub fn keys(&self, client_dst_connection_id: &[u8], side: Side, version: Version) -> Keys {
        Keys::initial(
            version,
            self.suite,
            self.quic,
            client_dst_connection_id,
            side,
        )
    }
}

/// Complete set of keys used to communicate with the peer
#[expect(clippy::exhaustive_structs)]
pub struct Keys {
    /// Encrypts outgoing packets
    pub local: DirectionalKeys,
    /// Decrypts incoming packets
    pub remote: DirectionalKeys,
}

impl Keys {
    /// Construct keys for use with initial packets
    pub fn initial(
        version: Version,
        suite: &'static Tls13CipherSuite,
        quic: &'static dyn Algorithm,
        client_dst_connection_id: &[u8],
        side: Side,
    ) -> Self {
        const CLIENT_LABEL: &[u8] = b"client in";
        const SERVER_LABEL: &[u8] = b"server in";
        let salt = version.initial_salt();
        let hs_secret = suite
            .hkdf_provider
            .extract_from_secret(Some(salt), client_dst_connection_id);

        let secrets = Secrets {
            client: hkdf_expand_label_block(hs_secret.as_ref(), CLIENT_LABEL, &[]),
            server: hkdf_expand_label_block(hs_secret.as_ref(), SERVER_LABEL, &[]),
            suite,
            quic,
            side,
            version,
        };
        Self::new(&secrets)
    }

    fn new(secrets: &Secrets) -> Self {
        let (local, remote) = secrets.local_remote();
        Self {
            local: DirectionalKeys::new(secrets.suite, secrets.quic, local, secrets.version),
            remote: DirectionalKeys::new(secrets.suite, secrets.quic, remote, secrets.version),
        }
    }
}

/// Key material for use in QUIC packet spaces
///
/// QUIC uses 4 different sets of keys (and progressive key updates for long-running connections):
///
/// * Initial: these can be created from [`Keys::initial()`]
/// * 0-RTT keys: can be retrieved from [`Connection::zero_rtt_keys()`]
/// * Handshake: these are returned from [`Connection::events()`] after `ClientHello` and
///   `ServerHello` messages have been exchanged
/// * 1-RTT keys: these are returned from [`Connection::events()`] after the handshake is done
///
/// Once the 1-RTT keys have been exchanged, either side may initiate a key update. Progressive
/// update keys can be obtained from the [`Secrets`] returned in [`KeyChange::OneRtt`]. Note that
/// only packet keys are updated by key updates; header protection keys remain the same.
#[expect(clippy::exhaustive_enums)]
pub enum KeyChange {
    /// Keys for the handshake space
    Handshake {
        /// Header and packet keys for the handshake space
        keys: Keys,
    },
    /// Keys for 1-RTT data
    OneRtt {
        /// Header and packet keys for 1-RTT data
        keys: Keys,
        /// Secrets to derive updated keys from
        next: Secrets,
    },
}

impl fmt::Debug for KeyChange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Handshake { .. } => f
                .debug_struct("Handshake")
                .finish_non_exhaustive(),
            Self::OneRtt { .. } => f
                .debug_struct("OneRtt")
                .finish_non_exhaustive(),
        }
    }
}

/// QUIC protocol version
///
/// Governs version-specific behavior in the TLS layer
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Version {
    /// First stable RFC
    #[default]
    V1,
    /// Anti-ossification variant of V1
    V2,
}

impl Version {
    fn initial_salt(self) -> &'static [u8; 20] {
        match self {
            Self::V1 => &[
                // https://www.rfc-editor.org/rfc/rfc9001.html#name-initial-secrets
                0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8,
                0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a,
            ],
            Self::V2 => &[
                // https://tools.ietf.org/html/rfc9369.html#name-initial-salt
                0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26,
                0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9,
            ],
        }
    }

    /// Key derivation label for packet keys.
    pub(crate) fn packet_key_label(&self) -> &'static [u8] {
        match self {
            Self::V1 => b"quic key",
            Self::V2 => b"quicv2 key",
        }
    }

    /// Key derivation label for packet "IV"s.
    pub(crate) fn packet_iv_label(&self) -> &'static [u8] {
        match self {
            Self::V1 => b"quic iv",
            Self::V2 => b"quicv2 iv",
        }
    }

    /// Key derivation for header keys.
    pub(crate) fn header_key_label(&self) -> &'static [u8] {
        match self {
            Self::V1 => b"quic hp",
            Self::V2 => b"quicv2 hp",
        }
    }

    fn key_update_label(&self) -> &'static [u8] {
        match self {
            Self::V1 => b"quic ku",
            Self::V2 => b"quicv2 ku",
        }
    }
}

#[cfg(all(test, any(target_arch = "aarch64", target_arch = "x86_64")))]
mod tests {
    use super::*;
    use crate::crypto::TLS13_TEST_SUITE;
    use crate::crypto::tls13::OkmBlock;
    use crate::quic::{HeaderProtectionKey, Secrets, Side, Version};

    #[test]
    fn key_update_test_vector() {
        fn equal_okm(x: &OkmBlock, y: &OkmBlock) -> bool {
            x.as_ref() == y.as_ref()
        }

        let mut secrets = Secrets {
            // Constant dummy values for reproducibility
            client: OkmBlock::new(
                &[
                    0xb8, 0x76, 0x77, 0x08, 0xf8, 0x77, 0x23, 0x58, 0xa6, 0xea, 0x9f, 0xc4, 0x3e,
                    0x4a, 0xdd, 0x2c, 0x96, 0x1b, 0x3f, 0x52, 0x87, 0xa6, 0xd1, 0x46, 0x7e, 0xe0,
                    0xae, 0xab, 0x33, 0x72, 0x4d, 0xbf,
                ][..],
            ),
            server: OkmBlock::new(
                &[
                    0x42, 0xdc, 0x97, 0x21, 0x40, 0xe0, 0xf2, 0xe3, 0x98, 0x45, 0xb7, 0x67, 0x61,
                    0x34, 0x39, 0xdc, 0x67, 0x58, 0xca, 0x43, 0x25, 0x9b, 0x87, 0x85, 0x06, 0x82,
                    0x4e, 0xb1, 0xe4, 0x38, 0xd8, 0x55,
                ][..],
            ),
            suite: TLS13_TEST_SUITE,
            quic: &FakeAlgorithm,
            side: Side::Client,
            version: Version::V1,
        };
        secrets.update();

        assert!(equal_okm(
            &secrets.client,
            &OkmBlock::new(
                &[
                    0x42, 0xca, 0xc8, 0xc9, 0x1c, 0xd5, 0xeb, 0x40, 0x68, 0x2e, 0x43, 0x2e, 0xdf,
                    0x2d, 0x2b, 0xe9, 0xf4, 0x1a, 0x52, 0xca, 0x6b, 0x22, 0xd8, 0xe6, 0xcd, 0xb1,
                    0xe8, 0xac, 0xa9, 0x6, 0x1f, 0xce
                ][..]
            )
        ));
        assert!(equal_okm(
            &secrets.server,
            &OkmBlock::new(
                &[
                    0xeb, 0x7f, 0x5e, 0x2a, 0x12, 0x3f, 0x40, 0x7d, 0xb4, 0x99, 0xe3, 0x61, 0xca,
                    0xe5, 0x90, 0xd4, 0xd9, 0x92, 0xe1, 0x4b, 0x7a, 0xce, 0x3, 0xc2, 0x44, 0xe0,
                    0x42, 0x21, 0x15, 0xb6, 0xd3, 0x8a
                ][..]
            )
        ));
    }

    struct FakeAlgorithm;

    impl Algorithm for FakeAlgorithm {
        fn packet_key(&self, _key: AeadKey, _iv: Iv) -> Box<dyn PacketKey> {
            unimplemented!()
        }

        fn header_protection_key(&self, _key: AeadKey) -> Box<dyn HeaderProtectionKey> {
            unimplemented!()
        }

        fn aead_key_len(&self) -> usize {
            16
        }
    }

    #[test]
    fn auto_traits() {
        fn assert_auto<T: Send + Sync>() {}
        assert_auto::<Box<dyn PacketKey>>();
        assert_auto::<Box<dyn HeaderProtectionKey>>();
    }
}