rustls 0.24.0-dev.2

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

use pki_types::FipsStatus;

pub use crate::common_state::Side;
use crate::common_state::{ConnectionOutputs, Protocol};
use crate::conn::{
    Accepted, Connection, MessageIter, MessageIterMode, ServerNext, SideData, Transport,
    VerifyPeerIdentity, sealed,
};
use crate::crypto::cipher::{AeadKey, Iv, Payload};
use crate::crypto::tls13::{Hkdf, HkdfExpander, OkmBlock};
use crate::error::{ApiMisuse, Error};
use crate::msgs::{Message, MessagePayload, ServerExtensionsInput, TransportParameters};
use crate::server::{ServerConfig, ServerSide};
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,
};
use crate::{ClientSide, TlsInputBuffer};
impl Connection<ServerSide, Quic> {
    /// Make a new QUIC server [`Connection`]
    ///
    /// This differs from `Connection::new()` in that it takes an extra `params` argument,
    /// which contains the TLS-encoded transport parameters to send.
    pub fn new_quic(
        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)),
            }),
        };

        Self::for_server(
            config,
            exts,
            Quic {
                version,
                ..Quic::default()
            },
        )
    }
}

/// 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<Quic>),

    /// The client's presented identity must be verified.
    ///
    /// See [`VerifyPeerIdentity<ServerSide, Quic>`] for how to proceed.
    VerifyClientIdentity(VerifyPeerIdentity<ServerSide, Quic>),

    /// The handshake is complete.
    Complete(Connection<ServerSide, Quic>),
}

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(Connection::for_acceptor(Quic {
            version,
            ..Quic::default()
        }))
    }
}

impl FromConn<ServerSide> for ServerHandshake {
    fn from_conn(
        mut conn: Connection<ServerSide, Quic>,
        output: &mut Vec<QuicEvent>,
    ) -> Result<Self, Error> {
        output.extend(conn.transport.events());

        Ok(match ServerNext::try_from(conn)? {
            ServerNext::NeedsInput(conn) => Self::NeedsInput(NeedsInput(conn)),

            ServerNext::ChooseConfig(accepted) => Self::Accepted(accepted),

            ServerNext::VerifyClientIdentity(verify) => Self::VerifyClientIdentity(verify),

            ServerNext::Complete(conn) => Self::Complete(conn),
        })
    }
}

impl Accepted<Quic> {
    /// 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(
        self,
        config: Arc<ServerConfig>,
        params: Vec<u8>,
        output: &mut Vec<QuicEvent>,
    ) -> Result<ServerHandshake, Error> {
        check_server_config(&config)?;

        let exts = ServerExtensionsInput {
            transport_parameters: Some(match self.conn.transport.version {
                Version::V1 | Version::V2 => TransportParameters::Quic(Payload::new(params)),
            }),
        };

        let mut tls = Vec::new();
        let conn = self.partial_choose_config(config, exts, &mut tls)?;

        // In QUIC mode, handshake output is emitted via `QuicEvent`s, not `tls`.
        debug_assert!(tls.is_empty());
        ServerHandshake::from_conn(conn, output)
    }
}

impl FromConn<ClientSide> for () {
    fn from_conn(
        _conn: Connection<ClientSide, Quic>,
        _output: &mut Vec<QuicEvent>,
    ) -> Result<(), Error> {
        todo!("nyi")
    }
}

pub(crate) trait FromConn<Side: SideData> {
    fn from_conn(
        conn: Connection<Side, Quic>,
        output: &mut Vec<QuicEvent>,
    ) -> Result<Side::QuicHandshake, Error>;
}

/// More data needs to be processed to make progress.
///
/// Provide the data to [`Self::process()`].
///
/// This type dereferences to [`ConnectionOutputs`]. Individual outputs are `None`
/// until they are learned during the handshake.
pub struct NeedsInput(Connection<ServerSide, Quic>);

impl NeedsInput {
    /// Return the TLS-encoded transport parameters received from the peer.
    ///
    /// While the transport parameters are available before the handshake completes,
    /// they cannot be fully trusted until then. Reliance on them should be minimized.
    /// Any tampering with the parameters will cause the handshake to fail.
    pub fn quic_transport_parameters(&self) -> Option<&[u8]> {
        self.0.transport.transport_parameters()
    }

    /// Compute the keys for decrypting 0-RTT packets, if available.
    pub fn zero_rtt_keys(&self) -> Option<DirectionalKeys> {
        self.0.transport.zero_rtt_keys(&self.0)
    }

    /// 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::VerifyClientIdentity`] if the client's identity requires
    ///   verification.
    /// - 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.0
            .common
            .recv
            .deframer
            .input_quic(input.slice_mut())?;

        self.0.process(input, &mut Vec::new())?;
        ServerHandshake::from_conn(self.0, output)
    }

    /// Returns data learned during the connection, specific to being a server.
    pub fn side(&self) -> &ServerSide {
        &self.0.side
    }
}

impl Deref for NeedsInput {
    type Target = ConnectionOutputs;

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

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

impl<Side: SideData> Connection<Side, Quic> {
    /// 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.
    pub fn read_hs(&mut self, input: &mut dyn TlsInputBuffer) -> Result<(), Error> {
        self.common
            .recv
            .deframer
            .input_quic(input.slice_mut())?;

        let mut tls = Vec::new();
        let mut iter = MessageIter::new(input, &mut tls, self, MessageIterMode::All);

        let result = match iter.next(false) {
            Some(Ok(_)) | None => Ok(()),
            Some(Err(e)) => Err(e),
        };

        input.discard(self.common.recv.deframer.take_discard());
        result
    }

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

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

    /// 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.
    pub fn quic_transport_parameters(&self) -> Option<&[u8]> {
        self.transport.transport_parameters()
    }
}

/// The QUIC transport: TLS handshake messages and key changes delivered as [`QuicEvent`]s.
#[derive(Default)]
pub 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()
    }

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

        let suite = Suite {
            inner: suite,
            quic: suite.quic?,
        };

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

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

impl Transport for Quic {}

impl sealed::Transport for Quic {
    fn protocol(&self) -> Protocol {
        Protocol::Quic(self.version)
    }

    fn quic(&mut self) -> Option<&mut dyn QuicOutput> {
        Some(self)
    }
}

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, secrets: SecretUpdate) {
        self.events
            .push(QuicEvent::KeyChange(KeyChange::Handshake {
                keys: Keys::new(&Secrets::new(secrets, self.version)),
            }));
    }

    fn traffic_secrets(&mut self, secrets: SecretUpdate) {
        let mut secrets = Secrets::new(secrets, 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, secrets: SecretUpdate);

    fn traffic_secrets(&mut self, secrets: SecretUpdate);

    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: Suite,
    side: Side,
    version: Version,
}

impl Secrets {
    pub(crate) fn new(update: SecretUpdate, version: Version) -> Self {
        Self {
            client: update.client,
            server: update.server,
            suite: update.suite,
            side: update.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
                .inner
                .hkdf_provider
                .expander_for_okm(&self.client)
                .as_ref(),
            self.version.key_update_label(),
            &[],
        );
        self.server = hkdf_expand_label_block(
            self.suite
                .inner
                .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),
        }
    }
}

pub(crate) struct SecretUpdate {
    pub(crate) client: OkmBlock,
    pub(crate) server: OkmBlock,
    pub(crate) suite: Suite,
    pub(crate) side: Side,
}

/// 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: Suite, secret: &OkmBlock, version: Version) -> Self {
        let builder = KeyBuilder::new(secret, version, suite.quic, suite.inner.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`] for this suite.
    ///
    /// `key` and `iv` is the key material to use.
    fn packet_key(&self, key: AeadKey, iv: Iv) -> Box<dyn PacketKey>;

    /// Produce a [`HeaderProtectionKey`] for this suite.
    ///
    /// `key` is the key material, which is [`Self::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 [`Self::packet_key()`] and
    /// [`Self::header_protection_key()`].
    fn aead_key_len(&self) -> usize;

    /// The FIPS validation status of this algorithm.
    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 packets that can be safely encrypted with a single key of this type.
    ///
    /// Once a `PacketKey` produced for this suite has encrypted more than
    /// `confidentiality_limit` packets, an attacker gains an advantage in distinguishing it
    /// from an ideal pseudorandom permutation (PRP).
    ///
    /// This is to be set on the assumption that packets 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 packets that can be safely decrypted with a single key of this type
    ///
    /// Once a `PacketKey` produced for this suite has failed to decrypt `integrity_limit`
    /// packets, an attacker gains an advantage in forging packets.
    ///
    /// 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.suite.quic,
            secrets.suite.inner.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 inner: &'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, client_dst_connection_id, side)
    }
}

impl TryFrom<&'static Tls13CipherSuite> for Suite {
    type Error = ApiMisuse;

    fn try_from(suite: &'static Tls13CipherSuite) -> Result<Self, Self::Error> {
        Ok(Self {
            inner: suite,
            quic: suite
                .quic
                .ok_or(ApiMisuse::NoQuicCompatibleCipherSuites)?,
        })
    }
}

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

/// 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: Suite,
        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
            .inner
            .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,
            side,
            version,
        };

        Self::new(&secrets)
    }

    fn new(secrets: &Secrets) -> Self {
        let (local, remote) = secrets.local_remote();
        Self {
            local: DirectionalKeys::new(secrets.suite, local, secrets.version),
            remote: DirectionalKeys::new(secrets.suite, 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, 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: Suite {
                inner: 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>>();
    }
}