gel-auth 0.1.7

Authentication and authorization for the Gel database.
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
//! # SCRAM (Salted Challenge Response Authentication Mechanism)
//!
//! SCRAM is a protocol that securely authenticates users by hashing and salting
//! their passwords before exchanging them, preventing exposure of the actual
//! password during transmission. It is commonly used in applications and
//! protocols like Postgres and SASL to enhance security against common attacks
//! such as replay and man-in-the-middle attacks.
//!
//! <https://en.wikipedia.org/wiki/Salted_Challenge_Response_Authentication_Mechanism>
//!
//! ## Limitations of this implementation
//!
//! This code implements a sufficient form of SCRAM to authenticate to most
//! PostgreSQL instances. It does not implement channel binding, and its
//! implementation is likely not generic enough to work with any other
//! implementation of SCRAM that isn't designed to be PostgreSQL-compatible.
//!
//! ## Transaction
//!
//! The transaction consists of four steps:
//!
//! 1. Client's Initial Response: The client sends its username and initial
//!    nonce.
//! 2. Server's Challenge: The server responds with a combined nonce, a
//!    base64-encoded salt, and an iteration count for the PBKDF2 algorithm.
//! 3. Client's Proof: The client sends its proof of possession of the password,
//!    along with the combined nonce and base64-encoded channel binding data.
//! 4. Server's Final Response: The server sends its verifier, proving
//!    successful authentication.
//!
//! This transaction securely authenticates the client to the server without
//! transmitting the actual password.
//!
//! ## Parameters
//!
//! The following parameters are used in the SCRAM authentication exchange:
//!
//! * `r=` (nonce): A random string generated by the client and server to ensure
//!   the uniqueness of each authentication exchange. The client initially sends
//!   its nonce, and the server responds with a combined nonce (client’s nonce +
//!   server’s nonce).
//!
//! * `c=` (channel binding): A base64-encoded representation of the channel
//!   binding data. This parameter is used to bind the authentication to the
//!   specific channel over which it is occurring, ensuring the integrity of the
//!   communication channel.
//!
//! * `s=` (salt): A base64-encoded salt provided by the server. The salt is
//!   used in conjunction with the client’s password to generate a salted
//!   password for enhanced security.
//!
//! * `i=` (iteration count): The number of iterations to apply in the PBKDF2
//!   (Password-Based Key Derivation Function 2) algorithm. This parameter
//!   defines the computational cost of generating the salted password.
//!
//! * `n=` (name): The username of the client. This parameter is included in the
//!   client’s initial response. Note that the username is sent out-of-band when
//!   using PostgreSQL and this parameter is set to an empty value.
//!
//! * `p=` (proof): The client’s proof of possession of the password. This is a
//!   base64-encoded value calculated using the salted password and other SCRAM
//!   parameters to prove that the client knows the password without sending it
//!   directly.
//!
//! * `v=` (verifier): The server’s verifier, which is used to prove that the
//!   server also knows the shared secret. This parameter is included in the
//!   server’s final message to confirm successful authentication.
#![allow(unused)]

use base64::{prelude::BASE64_STANDARD, Engine};
use hmac::{Hmac, Mac};
use rand::Rng;
use sha2::{digest::FixedOutput, Digest, Sha256};
use std::borrow::Cow;
use std::str::FromStr;

pub mod stringprep;
mod stringprep_table;

use stringprep::sasl_normalize_password_bytes;

const CHANNEL_BINDING_ENCODED: &str = "biws";
const MINIMUM_NONCE_LENGTH: usize = 16;

type HmacSha256 = Hmac<Sha256>;
pub type Sha256Out = [u8; 32];

#[derive(Debug, derive_more::Error, derive_more::Display)]
pub enum SCRAMError {
    #[display("Invalid encoding")]
    ProtocolError,
}

pub trait ServerEnvironment {
    fn get_password_parameters(&self, username: &str) -> (Cow<'static, [u8]>, usize);
    fn get_stored_key(&self, username: &str) -> (Sha256Out, Sha256Out);
    fn generate_nonce(&self) -> String;
}

#[derive(Default, derive_more::Debug)]
pub struct ServerTransaction {
    #[debug(skip)]
    state: ServerState,
}

impl ServerTransaction {
    pub fn success(&self) -> bool {
        matches!(self.state, ServerState::Success)
    }

    pub fn initial(&self) -> bool {
        matches!(self.state, ServerState::Initial)
    }

    pub fn process_message(
        &mut self,
        message: &[u8],
        env: &impl ServerEnvironment,
    ) -> Result<Vec<u8>, SCRAMError> {
        match &self.state {
            ServerState::Success => Err(SCRAMError::ProtocolError),
            ServerState::Initial => {
                let message = ClientFirstMessage::decode(message)?;
                if message.channel_binding != ChannelBinding::NotSupported("".into()) {
                    return Err(SCRAMError::ProtocolError);
                }
                if message.nonce.len() < MINIMUM_NONCE_LENGTH {
                    return Err(SCRAMError::ProtocolError);
                }
                let (salt, iterations) = env.get_password_parameters(&message.username);
                let mut nonce = message.nonce.to_string();
                nonce += &env.generate_nonce();
                let response = ServerFirstResponse {
                    combined_nonce: nonce.to_string().into(),
                    salt: BASE64_STANDARD.encode(salt).into(),
                    iterations,
                };
                self.state =
                    ServerState::SentChallenge(message.to_owned_bare(), response.to_owned());
                Ok(response.encode().into_bytes())
            }
            ServerState::SentChallenge(first_message, first_response) => {
                let message = ClientFinalMessage::decode(message)?;
                if !constant_time_eq::constant_time_eq(
                    message.combined_nonce.as_bytes(),
                    first_response.combined_nonce.as_bytes(),
                ) {
                    return Err(SCRAMError::ProtocolError);
                }
                if message.channel_binding != CHANNEL_BINDING_ENCODED {
                    return Err(SCRAMError::ProtocolError);
                }
                let (stored_key, server_key) = env.get_stored_key(&first_message.username);

                // Decode the provided client proof
                let mut provided_proof = vec![];
                BASE64_STANDARD
                    .decode_vec(message.proof.as_bytes(), &mut provided_proof)
                    .map_err(|_| SCRAMError::ProtocolError)?;

                let (calculated_stored_key, server_signature) = generate_server_proof(
                    first_message.encode().as_bytes(),
                    first_response.encode().as_bytes(),
                    message.channel_binding.as_bytes(),
                    message.combined_nonce.as_bytes(),
                    &provided_proof,
                    &server_key,
                    &stored_key,
                );

                if !constant_time_eq::constant_time_eq(
                    calculated_stored_key.as_slice(),
                    &stored_key,
                ) {
                    return Err(SCRAMError::ProtocolError);
                }

                self.state = ServerState::Success;
                let verifier = BASE64_STANDARD.encode(server_signature).into();
                Ok(ServerFinalResponse { verifier }.encode().into_bytes())
            }
        }
    }
}

#[derive(Default)]
enum ServerState {
    #[default]
    Initial,
    SentChallenge(ClientFirstMessage<'static>, ServerFirstResponse<'static>),
    Success,
}

pub trait ClientEnvironment {
    fn get_salted_password(&self, salt: &[u8], iterations: usize) -> Sha256Out;
    fn generate_nonce(&self) -> String;
}

#[derive(Debug)]
pub struct ClientTransaction {
    state: ClientState,
}

impl ClientTransaction {
    pub fn new(username: Cow<'static, str>) -> Self {
        Self {
            state: ClientState::Initial(username),
        }
    }

    pub fn success(&self) -> bool {
        matches!(self.state, ClientState::Success)
    }

    pub fn process_message(
        &mut self,
        message: &[u8],
        env: &impl ClientEnvironment,
    ) -> Result<Option<Vec<u8>>, SCRAMError> {
        match &self.state {
            ClientState::Success => Err(SCRAMError::ProtocolError),
            ClientState::Initial(username) => {
                if !message.is_empty() {
                    return Err(SCRAMError::ProtocolError);
                }
                let nonce = env.generate_nonce().into();
                let message = ClientFirstMessage {
                    channel_binding: ChannelBinding::NotSupported("".into()),
                    username: username.clone(),
                    nonce,
                };
                self.state = ClientState::SentFirst(message.to_owned_bare());
                Ok(Some(message.encode().into_bytes()))
            }
            ClientState::SentFirst(first_message) => {
                let message = ServerFirstResponse::decode(message)?;
                // Ensure the client nonce was concatenated with the server's nonce
                if !message
                    .combined_nonce
                    .starts_with(first_message.nonce.as_ref())
                {
                    return Err(SCRAMError::ProtocolError);
                }
                if message.combined_nonce.len() - first_message.nonce.len() < MINIMUM_NONCE_LENGTH {
                    return Err(SCRAMError::ProtocolError);
                }
                let mut buffer = [0; 1024];
                let salt = decode_salt(&message.salt, &mut buffer)?;
                let salted_password = env.get_salted_password(&salt, message.iterations);
                let (client_proof, server_verifier) = generate_client_proof(
                    first_message.encode().as_bytes(),
                    message.encode().as_bytes(),
                    CHANNEL_BINDING_ENCODED.as_bytes(),
                    message.combined_nonce.as_bytes(),
                    &salted_password,
                );
                let message = ClientFinalMessage {
                    channel_binding: CHANNEL_BINDING_ENCODED.into(),
                    combined_nonce: message.combined_nonce.to_string().into(),
                    proof: BASE64_STANDARD.encode(client_proof).into(),
                };
                self.state = ClientState::ExpectingVerifier(ServerFinalResponse {
                    verifier: BASE64_STANDARD.encode(server_verifier).into(),
                });
                Ok(Some(message.encode().into_bytes()))
            }
            ClientState::ExpectingVerifier(server_final_response) => {
                let message = ServerFinalResponse::decode(message)?;
                if !constant_time_eq::constant_time_eq(
                    message.verifier.as_bytes(),
                    server_final_response.verifier.as_bytes(),
                ) {
                    return Err(SCRAMError::ProtocolError);
                }
                self.state = ClientState::Success;
                Ok(None)
            }
        }
    }
}

#[derive(Debug)]
enum ClientState {
    Initial(Cow<'static, str>),
    SentFirst(ClientFirstMessage<'static>),
    ExpectingVerifier(ServerFinalResponse<'static>),
    Success,
}

trait Encode {
    fn encode(&self) -> String;
}

trait Decode<'a> {
    fn decode(buf: &'a [u8]) -> Result<Self, SCRAMError>
    where
        Self: Sized + 'a;
}

fn extract<'a>(input: &'a [u8], prefix: &'static str) -> Result<&'a str, SCRAMError> {
    let bytes = input
        .strip_prefix(prefix.as_bytes())
        .ok_or(SCRAMError::ProtocolError)?;
    std::str::from_utf8(bytes).map_err(|_| SCRAMError::ProtocolError)
}

fn inext<'a>(it: &mut impl Iterator<Item = &'a [u8]>) -> Result<&'a [u8], SCRAMError> {
    it.next().ok_or(SCRAMError::ProtocolError)
}

fn hmac(s: &[u8]) -> HmacSha256 {
    // This is effectively infallible
    HmacSha256::new_from_slice(s).expect("HMAC can take key of any size")
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// `gs2-cbind-flag` from RFC5802.
enum ChannelBinding<'a> {
    /// No channel binding
    NotSpecified,
    /// "n" -> client doesn't support channel binding.
    NotSupported(Cow<'a, str>),
    /// "y" -> client does support channel binding but thinks the server does
    /// not.
    Supported(Cow<'a, str>),
    /// "p" -> client requires channel binding. The selected channel binding
    /// follows "p=".
    Required(Cow<'a, str>, Cow<'a, str>),
}

#[derive(Debug)]
pub struct ClientFirstMessage<'a> {
    channel_binding: ChannelBinding<'a>,
    username: Cow<'a, str>,
    nonce: Cow<'a, str>,
}

impl ClientFirstMessage<'_> {
    /// Get the bare first message
    pub fn to_owned_bare(&self) -> ClientFirstMessage<'static> {
        ClientFirstMessage {
            channel_binding: ChannelBinding::NotSpecified,
            username: self.username.to_string().into(),
            nonce: self.nonce.to_string().into(),
        }
    }
}

impl Encode for ClientFirstMessage<'_> {
    fn encode(&self) -> String {
        let channel_binding = match self.channel_binding {
            ChannelBinding::NotSpecified => "".to_string(),
            ChannelBinding::NotSupported(ref s) => format!("n,{s},"),
            ChannelBinding::Supported(ref s) => format!("y,{s},"),
            ChannelBinding::Required(ref s, ref t) => format!("p={t},{s},"),
        };
        format!("{channel_binding}n={},r={}", self.username, self.nonce)
    }
}

impl<'a> Decode<'a> for ClientFirstMessage<'a> {
    fn decode(buf: &'a [u8]) -> Result<Self, SCRAMError> {
        let mut parts = buf.split(|&b| b == b',');

        // Check for channel binding
        let mut next = inext(&mut parts)?;
        let mut channel_binding = ChannelBinding::NotSpecified;
        match (next.len(), next.first()) {
            (_, Some(b'p')) => {
                // p=(cb-name),(authz-id),
                let Some(cb_name) = next.strip_prefix(b"p=") else {
                    return Err(SCRAMError::ProtocolError);
                };
                let cb_name =
                    std::str::from_utf8(cb_name).map_err(|_| SCRAMError::ProtocolError)?;
                let param = inext(&mut parts)?;
                channel_binding = ChannelBinding::Required(
                    Cow::Borrowed(
                        std::str::from_utf8(param).map_err(|_| SCRAMError::ProtocolError)?,
                    ),
                    cb_name.into(),
                );
                next = inext(&mut parts)?;
            }
            (1, Some(b'n')) => {
                let param = inext(&mut parts)?;
                channel_binding = ChannelBinding::NotSupported(Cow::Borrowed(
                    std::str::from_utf8(param).map_err(|_| SCRAMError::ProtocolError)?,
                ));
                next = inext(&mut parts)?;
            }
            (1, Some(b'y')) => {
                let param = inext(&mut parts)?;
                channel_binding = ChannelBinding::Supported(Cow::Borrowed(
                    std::str::from_utf8(param).map_err(|_| SCRAMError::ProtocolError)?,
                ));
                next = inext(&mut parts)?;
            }
            (_, None) => {
                return Err(SCRAMError::ProtocolError);
            }
            _ => {
                // No channel binding specified
            }
        }
        let username = extract(next, "n=")?.into();
        let nonce = extract(inext(&mut parts)?, "r=")?.into();
        Ok(ClientFirstMessage {
            channel_binding,
            username,
            nonce,
        })
    }
}

pub struct ServerFirstResponse<'a> {
    combined_nonce: Cow<'a, str>,
    salt: Cow<'a, str>,
    iterations: usize,
}

impl ServerFirstResponse<'_> {
    pub fn to_owned(&self) -> ServerFirstResponse<'static> {
        ServerFirstResponse {
            combined_nonce: self.combined_nonce.to_string().into(),
            salt: self.salt.to_string().into(),
            iterations: self.iterations,
        }
    }
}

impl Encode for ServerFirstResponse<'_> {
    fn encode(&self) -> String {
        format!(
            "r={},s={},i={}",
            self.combined_nonce, self.salt, self.iterations
        )
    }
}

impl<'a> Decode<'a> for ServerFirstResponse<'a> {
    fn decode(buf: &'a [u8]) -> Result<Self, SCRAMError> {
        let mut parts = buf.split(|&b| b == b',');
        let combined_nonce = extract(inext(&mut parts)?, "r=")?.into();
        let salt = extract(inext(&mut parts)?, "s=")?.into();
        let iterations = extract(inext(&mut parts)?, "i=")?;
        Ok(ServerFirstResponse {
            combined_nonce,
            salt,
            iterations: str::parse(iterations).map_err(|_| SCRAMError::ProtocolError)?,
        })
    }
}

pub struct ClientFinalMessage<'a> {
    channel_binding: Cow<'a, str>,
    combined_nonce: Cow<'a, str>,
    proof: Cow<'a, str>,
}

impl Encode for ClientFinalMessage<'_> {
    fn encode(&self) -> String {
        format!(
            "c={},r={},p={}",
            self.channel_binding, self.combined_nonce, self.proof
        )
    }
}

impl<'a> Decode<'a> for ClientFinalMessage<'a> {
    fn decode(buf: &'a [u8]) -> Result<Self, SCRAMError> {
        let mut parts = buf.split(|&b| b == b',');
        let channel_binding = extract(inext(&mut parts)?, "c=")?.into();
        let combined_nonce = extract(inext(&mut parts)?, "r=")?.into();
        let proof = extract(inext(&mut parts)?, "p=")?.into();
        Ok(ClientFinalMessage {
            channel_binding,
            combined_nonce,
            proof,
        })
    }
}

#[derive(Debug)]
pub struct ServerFinalResponse<'a> {
    verifier: Cow<'a, str>,
}

impl Encode for ServerFinalResponse<'_> {
    fn encode(&self) -> String {
        format!("v={}", self.verifier)
    }
}

impl<'a> Decode<'a> for ServerFinalResponse<'a> {
    fn decode(buf: &'a [u8]) -> Result<Self, SCRAMError> {
        let mut parts = buf.split(|&b| b == b',');
        let verifier = extract(inext(&mut parts)?, "v=")?.into();
        Ok(ServerFinalResponse { verifier })
    }
}

pub fn decode_salt<'a>(salt: &str, buffer: &'a mut [u8]) -> Result<Cow<'a, [u8]>, SCRAMError> {
    // The salt needs to be base64 decoded -- full binary must be used
    if let Ok(n) = BASE64_STANDARD.decode_slice(salt, buffer) {
        Ok(Cow::Borrowed(&buffer[..n]))
    } else {
        // In the unlikely case the salt is large -- note that we also fall back to this
        // path for invalid base64 strings!
        let mut buffer = vec![];
        BASE64_STANDARD
            .decode_vec(salt, &mut buffer)
            .map_err(|_| SCRAMError::ProtocolError)?;
        Ok(Cow::Owned(buffer))
    }
}

/// Given a password in byte form, generates the salted version of the password,
/// applying SASLprep to it beforehand.
pub fn generate_salted_password(password: &[u8], salt: &[u8], iterations: usize) -> Sha256Out {
    // Save the pre-keyed hmac
    let ui_p = hmac(&sasl_normalize_password_bytes(password));

    // The initial signature is the salt with a terminator of a 32-bit string ending in 1
    let mut ui = ui_p.clone();

    ui.update(salt);
    ui.update(&[0, 0, 0, 1]);

    // Grab the initial digest
    let mut last_hash = Default::default();
    ui.finalize_into(&mut last_hash);
    let mut u = last_hash;

    // For X number of iterations, recompute the HMAC signature against the password and the latest iteration of the hash, and XOR it with the previous version
    for _ in 0..(iterations - 1) {
        let mut ui = ui_p.clone();
        ui.update(&last_hash);
        ui.finalize_into(&mut last_hash);
        for i in 0..u.len() {
            u[i] ^= last_hash[i];
        }
    }

    u.as_slice().try_into().unwrap()
}

pub fn generate_nonce() -> String {
    let bytes: [u8; 32] = rand::random();
    BASE64_STANDARD.encode(bytes)
}

/// A stored SCRAM-SHA-256 key.
///
/// The SCRAM key format consists of several components separated by '$' and ':'
/// characters:
///
/// `"SCRAM-SHA-256$<iterations>:<salt>$<stored_key>:<server_key>"`
///
/// Where:
///  - `iterations`: Number of PBKDF2-HMAC-SHA256 iterations used for key
///    derivation
///  - `salt`: Base64-encoded cryptographically secure random salt used in key
///    derivation
///  - `stored_key`: Hash of the client key, where client key is derived as
///    `SHA-256(HMAC-SHA-256(salted_password, "Client Key"))`
///  - `server_key`: Server key derived as `HMAC-SHA-256(salted_password,
///    "Server Key")`
///
/// The `stored_key` and `server_key` are pre-computed cryptographic values that
/// prevent storing the raw password while maintaining secure authentication.
/// The `stored_key` is a `hash(hmac(P, ...))` used to verify client
/// authentication proofs, while the `server_key` is a `hmac(P, ...)` used to
/// generate server authentication signatures.
#[derive(Clone, Debug)]
pub struct StoredKey {
    pub iterations: usize,
    pub salt: Vec<u8>,
    pub stored_key: Sha256Out,
    pub server_key: Sha256Out,
}

impl PartialEq for StoredKey {
    fn eq(&self, other: &Self) -> bool {
        // If the salt and stored_key match, the remainder must match.
        // We only need to compare these two fields for equality because:
        // 1. The salt is used to derive the stored_key, so if both match,
        //    it implies the same password and iteration count were used.
        // 2. The server_key is derived from the same process, so it will
        //    automatically match if the salt and stored_key match.
        // 3. The iterations count doesn't need to be compared explicitly
        //    as it's factored into the stored_key calculation.
        constant_time_eq::constant_time_eq(&self.salt, &other.salt)
            && constant_time_eq::constant_time_eq(&self.stored_key, &other.stored_key)
    }
}

impl Eq for StoredKey {}

impl FromStr for StoredKey {
    type Err = SCRAMError;

    // "SCRAM-SHA-256$<iterations>:<salt>$<stored_key>:<server_key>"

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('$').collect();
        if parts.len() != 3 || parts[0] != "SCRAM-SHA-256" {
            return Err(SCRAMError::ProtocolError);
        }

        let iterations = parts[1]
            .split(':')
            .next()
            .ok_or(SCRAMError::ProtocolError)?
            .parse()
            .map_err(|_| SCRAMError::ProtocolError)?;

        let salt = BASE64_STANDARD
            .decode(
                parts[1]
                    .split(':')
                    .nth(1)
                    .ok_or(SCRAMError::ProtocolError)?,
            )
            .map_err(|_| SCRAMError::ProtocolError)?;

        let key_parts: Vec<&str> = parts[2].split(':').collect();
        if key_parts.len() != 2 {
            return Err(SCRAMError::ProtocolError);
        }

        let stored_key = BASE64_STANDARD
            .decode(key_parts[0])
            .map_err(|_| SCRAMError::ProtocolError)?
            .try_into()
            .map_err(|_| SCRAMError::ProtocolError)?;

        let server_key = BASE64_STANDARD
            .decode(key_parts[1])
            .map_err(|_| SCRAMError::ProtocolError)?
            .try_into()
            .map_err(|_| SCRAMError::ProtocolError)?;

        Ok(StoredKey {
            iterations,
            salt,
            stored_key,
            server_key,
        })
    }
}
use std::fmt;

impl fmt::Display for StoredKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SCRAM-SHA-256${}:{}${}:{}",
            self.iterations,
            BASE64_STANDARD.encode(&self.salt),
            BASE64_STANDARD.encode(self.stored_key),
            BASE64_STANDARD.encode(self.server_key)
        )
    }
}

impl ServerEnvironment for StoredKey {
    fn get_password_parameters(&self, username: &str) -> (Cow<'static, [u8]>, usize) {
        (Cow::Owned(self.salt.clone()), self.iterations)
    }

    fn generate_nonce(&self) -> String {
        let nonce: [u8; 32] = rand::random();
        base64::engine::general_purpose::STANDARD.encode(nonce)
    }

    fn get_stored_key(&self, username: &str) -> (Sha256Out, Sha256Out) {
        (self.stored_key, self.server_key)
    }
}

impl StoredKey {
    /// Generate a stored key compatible with PostgreSQL's encoding.
    pub fn generate(password: &[u8], salt: &[u8], iterations: usize) -> Self {
        let digest_key = generate_salted_password(password, salt, iterations);

        let client_key = hmac(&digest_key)
            .chain_update(b"Client Key")
            .finalize()
            .into_bytes();

        let stored_key = Sha256::digest(client_key);

        let server_key = hmac(&digest_key)
            .chain_update(b"Server Key")
            .finalize()
            .into_bytes();

        Self {
            iterations,
            salt: salt.to_owned(),
            stored_key: stored_key.into(),
            server_key: server_key.into(),
        }
    }
}

fn generate_client_proof(
    first_message_bare: &[u8],
    server_first_message: &[u8],
    channel_binding: &[u8],
    server_nonce: &[u8],
    salted_password: &[u8],
) -> (Sha256Out, Sha256Out) {
    let ui_p = hmac(salted_password);

    let mut ui = ui_p.clone();
    ui.update(b"Server Key");
    let server_key = ui.finalize_fixed();

    let mut ui = ui_p.clone();
    ui.update(b"Client Key");
    let client_key = ui.finalize_fixed();

    let mut hash = Sha256::new();
    hash.update(client_key);
    let stored_key = hash.finalize_fixed();

    let auth_message = [
        (first_message_bare),
        (b","),
        (server_first_message),
        (b",c="),
        (channel_binding),
        (b",r="),
        (server_nonce),
    ];

    let mut client_signature = hmac(&stored_key);
    for chunk in auth_message {
        client_signature.update(chunk);
    }

    let client_signature = client_signature.finalize_fixed();
    let mut client_signature: Sha256Out = client_signature.as_slice().try_into().unwrap();

    for i in 0..client_signature.len() {
        client_signature[i] ^= client_key[i];
    }

    let mut server_proof = hmac(&server_key);
    for chunk in auth_message {
        server_proof.update(chunk);
    }
    let server_proof = server_proof.finalize_fixed().as_slice().try_into().unwrap();

    (client_signature, server_proof)
}

fn generate_server_proof(
    first_message_bare: &[u8],
    server_first_message: &[u8],
    channel_binding: &[u8],
    server_nonce: &[u8],
    provided_proof: &[u8],
    server_key: &[u8],
    stored_key: &[u8],
) -> (Sha256Out, Sha256Out) {
    let auth_message = [
        (first_message_bare),
        (b","),
        (server_first_message),
        (b",c="),
        (channel_binding),
        (b",r="),
        (server_nonce),
    ];

    let mut client_signature = hmac(stored_key);
    for chunk in &auth_message {
        client_signature.update(chunk);
    }
    let client_signature = client_signature.finalize_fixed();

    let mut calculated_stored_key = [0u8; 32];
    for (i, (&p, &c)) in provided_proof
        .iter()
        .zip(client_signature.iter())
        .enumerate()
    {
        calculated_stored_key[i] = p ^ c;
    }

    let calculated_stored_key = Sha256::digest(calculated_stored_key);

    let mut server_signature = hmac(server_key);
    for chunk in &auth_message {
        server_signature.update(chunk);
    }
    let server_signature = server_signature.finalize_fixed();

    (calculated_stored_key.into(), server_signature.into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use hex_literal::hex;
    use pretty_assertions::{assert_eq, assert_ne};
    use rstest::rstest;

    // Define a set of test parameters
    const CLIENT_NONCE: &str = "2XendqvQOa6cl0+Q7Y6UU0gw";
    const SERVER_NONCE: &str = "xWn3mvDeVZwnUtT09vwXoItO";
    const USERNAME: &str = "";
    const PASSWORD: &[u8] = b"secret";
    const SALT: &str = "t5YekvL6lgy4RyPnsiyqsg==";
    const ITERATIONS: usize = 4096;
    const CLIENT_PROOF: &[u8] = "p/HmDcOziQQnyF8fbVnJnlvwoLp1kZY4xsI9cCJhzCE=".as_bytes();
    const SERVER_VERIFY: &[u8] = "g/X0codOryF0nCOWh7KkIab23ZFPX99iLzN5Ghn3nNc=".as_bytes();

    #[rstest]
    #[case(
        b"1234",
        "1234",
        1,
        hex!("EBE7E5BA4BF5A4D178D3BADAADD4C49A98C72FCFF4FB357DA7090D584990FCAA")
    )]
    #[case(
        b"1234",
        "1234",
        2,
        hex!("F9271C334EE6CD7FEE63BBC86FAF951A4ED9E293BDD72AC33663BAE662D31953")
    )]
    #[case(
        b"1234",
        "1234",
        4096,
        hex!("4FF8D6443278AB43209DF5A1327949AAC99A5AA23921E5C9199626524776F751")
    )]
    #[case(
        b"password",
        "480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu",
        4096,
        hex!("E118A9AD43C87938659AD736E63F26BA2EBAF079AA351DB44AE29228FB4F7EF0")
    )]
    #[case(
        b"secret",
        "480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu",
        4096,
        hex!("77DFD8E62A4379296C9769F9BA2F77D503C4647DE7919B47D6CF121986981BCC")
    )]
    #[case(
        b"secret",
        "t5YekvL6lgy4RyPnsiyqsg==",
        4096,
        hex!("9FB413FE9F1D0C8020400A3D49CFBC47FBFB1251CEA9297630BD025DB2B65171")
    )]
    #[case(
        "😀".as_bytes(),
        "t5YekvL6lgy4RyPnsiyqsg==",
        4096,
        hex!("AF490CE1BEA2DDB585DAF9C3842D1528AB091EF6FAB2A92489870523A98835EE")
    )]
    fn test_generate_salted_password(
        #[case] password: &[u8],
        #[case] salt: &str,
        #[case] iterations: usize,
        #[case] expected_hash: Sha256Out,
    ) {
        let mut buffer = [0; 128];
        let salt = decode_salt(salt, &mut buffer).unwrap();
        let hash = generate_salted_password(password, &salt, iterations);
        assert_eq!(hash, expected_hash);
    }

    /// Tests that use real stored keys from postgres to match normalization
    /// behaviour. This exercises the saslprep code indirectly to ensure it
    /// matches the PostgreSQL implementation.
    ///
    /// Passwords in these tests were generated via `ALTER ROLE` DDL statements,
    /// and the salted password was then extracted from the roles table.
    ///
    /// Note that a PostgreSQL user may have a password that is only value when
    /// interpreted as a bag of bytes and cannot be set directly via `ALTER
    /// ROLE` or the `initdb` command-line. This code _should_ support those
    /// passwords, however given the complexity of testing this we do not
    /// currently do so. Should we wish to test this in the future, we will need
    /// to manually create the stored key, set this string as the password for
    /// the role, and then validate that it can be used to authenticate via
    /// SCRAM.
    #[rstest]
    // ASCII
    #[case(b"password", "SCRAM-SHA-256$4096:jZLwuMbICV2L8i9SsfSEYQ==$Qhd2nOIlLW/dtVFERkVjVNdzzrVwPm2l+WHibmPesoc=:P1aH2cUHyPUbIdO06hEiXdwKxQyqBNUijLGFLkTXcHs=")]
    // Unicode
    #[case("schön".as_bytes(), "SCRAM-SHA-256$4096:uuH6VXsbbeId2AcdL0WmSA==$imMseND/Sg7tL5Tm1ltZJGa6PsdxwysUZ9s1lXPOPdo=:kMp6Rb9yN3zYpvwkuf0/xQZWhIGEa0ryjwnyDfpL3G0=")]
    // Unicode normalization -> half-width to full-width
    #[case("パスワード".as_bytes(), "SCRAM-SHA-256$4096:oCSGmW9Llo803DWp94yE0A==$TvNA2Hh1IqwCHlhxHhIaTeI7N/mFSx01D3/tb2VGQfw=:RBDsZImb7XoP6Md1j0zhjf7yBz0ocDoxqsPeFtJLyaI=")]
    // Chars that normalize to space and nothing
    #[case(b"pass\xc2\xa0\xe2\x80\x80word", "SCRAM-SHA-256$4096:ag3Z1WnqEn8dhTvSP7UtYA==$taWe9cZJYK5Y28V9Nw3zy6E9qQKbqKrMRS5DwlDXG04=:Y4n3uwZ4jQyG7nYCde3vtPxO1p0Oxz5ytJT1W+lqM+I=")]
    // Invalid control chars
    #[case(b"\x01\x02\x03", "SCRAM-SHA-256$4096:XGcYpEn2cwuS+BZXJBaqFg==$mG53wGoI6pAANoAZl7qxYiKPZ6u3CfhCVZK4et3l52A=:X5PUFkC5MVJWmuBTwWQHTFH81xjiyAHrJ9r0anOPXiI=")]
    // Prohibited char (ffff)
    #[case(b"\xef\xbf\xbf", "SCRAM-SHA-256$4096:Tdv5eCJIm+LU9QJBKO96gQ==$YXE4G3HKPwCmwo4FjiFKaiqVGCDTOpVETv+Fe6wWY9Q=:DK7MZ/OgGGgCDh6EfsmmcyFuaAD+T2Zh78sl+QDQFIo=")]
    fn test_stored_key(#[case] password: &[u8], #[case] stored_key: &str) {
        let parsed_key = StoredKey::from_str(stored_key).unwrap();
        assert_eq!(4096, parsed_key.iterations);
        let generated_key = StoredKey::generate(password, &parsed_key.salt, parsed_key.iterations);
        assert_eq!(generated_key, parsed_key);
        assert_eq!(generated_key.to_string(), stored_key);
    }

    #[test]
    fn test_client_proof() {
        let mut buffer = [0; 128];
        let salt = decode_salt(SALT, &mut buffer).unwrap();
        let salted_password = generate_salted_password(PASSWORD, &salt, ITERATIONS);
        let (client, server) = generate_client_proof(
            format!("n={USERNAME},r={CLIENT_NONCE}").as_bytes(),
            format!("r={CLIENT_NONCE}{SERVER_NONCE},s={SALT},i={ITERATIONS}").as_bytes(),
            CHANNEL_BINDING_ENCODED.as_bytes(),
            format!("{CLIENT_NONCE}{SERVER_NONCE}").as_bytes(),
            &salted_password,
        );
        assert_eq!(
            &client,
            BASE64_STANDARD.decode(CLIENT_PROOF).unwrap().as_slice()
        );
        assert_eq!(
            &server,
            BASE64_STANDARD.decode(SERVER_VERIFY).unwrap().as_slice()
        );
    }

    #[test]
    fn test_client_first_message() {
        let message = ClientFirstMessage::decode(b"n,,n=,r=480I9uIaXEU9oB2RRcenOxN/").unwrap();
        assert_eq!(
            message.channel_binding,
            ChannelBinding::NotSupported(Cow::Borrowed(""))
        );
        assert_eq!(message.username, "");
        assert_eq!(message.nonce, "480I9uIaXEU9oB2RRcenOxN/");
        assert_eq!(
            message.encode(),
            "n,,n=,r=480I9uIaXEU9oB2RRcenOxN/".to_owned()
        );
    }

    #[test]
    fn test_client_first_message_required() {
        let message =
            ClientFirstMessage::decode(b"p=cb-name,,n=,r=480I9uIaXEU9oB2RRcenOxN/").unwrap();
        assert_eq!(
            message.channel_binding,
            ChannelBinding::Required(Cow::Borrowed(""), Cow::Borrowed("cb-name"))
        );
        assert_eq!(message.username, "");
        assert_eq!(message.nonce, "480I9uIaXEU9oB2RRcenOxN/");
        assert_eq!(
            message.encode(),
            "p=cb-name,,n=,r=480I9uIaXEU9oB2RRcenOxN/".to_owned()
        );
    }

    #[test]
    fn test_server_first_response() {
        let message = ServerFirstResponse::decode(
            b"r=480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu,s=t5YekvL6lgy4RyPnsiyqsg==,i=4096",
        )
        .unwrap();
        assert_eq!(
            message.combined_nonce,
            "480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu"
        );
        assert_eq!(message.salt, "t5YekvL6lgy4RyPnsiyqsg==");
        assert_eq!(message.iterations, 4096);
        assert_eq!(
            message.encode(),
            "r=480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu,s=t5YekvL6lgy4RyPnsiyqsg==,i=4096"
                .to_owned()
        );
    }

    #[test]
    fn test_client_final_message() {
        let message = b"c=biws,r=480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu,p=7Vkz4SfWTNhB3hNdhTucC+3MaGmg3+PrAG3xfuepjP4=";
        let decoded = ClientFinalMessage::decode(message).unwrap();
        assert_eq!(decoded.channel_binding, "biws");
        assert_eq!(
            decoded.combined_nonce,
            "480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu"
        );
        assert_eq!(
            decoded.proof,
            "7Vkz4SfWTNhB3hNdhTucC+3MaGmg3+PrAG3xfuepjP4="
        );
        let encoded = decoded.encode();
        assert_eq!(encoded, "c=biws,r=480I9uIaXEU9oB2RRcenOxN/RsOCy0BKJvyRSeuOtQ0cF0hu,p=7Vkz4SfWTNhB3hNdhTucC+3MaGmg3+PrAG3xfuepjP4=");
    }

    #[test]
    fn test_server_final_response() {
        let message = b"v=6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4=";
        let decoded: ServerFinalResponse = ServerFinalResponse::decode(message).unwrap();
        assert_eq!(
            decoded.verifier,
            "6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4="
        );
        let encoded = decoded.encode();
        assert_eq!(encoded, "v=6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4=");
    }

    /// Run a SCRAM conversation with a fixed set of parameters
    #[test]
    fn test_transaction() {
        let mut server = ServerTransaction::default();
        let mut client = ClientTransaction::new("username".into());

        struct Env {}
        impl ClientEnvironment for Env {
            fn generate_nonce(&self) -> String {
                "<<<client nonce>>>".into()
            }
            fn get_salted_password(&self, salt: &[u8], iterations: usize) -> Sha256Out {
                generate_salted_password(b"password", salt, iterations)
            }
        }
        impl ServerEnvironment for Env {
            fn get_stored_key(&self, username: &str) -> (Sha256Out, Sha256Out) {
                assert_eq!(username, "username");
                let key = StoredKey::generate(b"password", b"hello", 4096);
                (key.stored_key, key.server_key)
            }
            fn generate_nonce(&self) -> String {
                "<<<server nonce>>>".into()
            }
            fn get_password_parameters(&self, username: &str) -> (Cow<'static, [u8]>, usize) {
                assert_eq!(username, "username");
                (Cow::Borrowed(b"hello"), 4096)
            }
        }
        let env = Env {};
        let message = client.process_message(&[], &env).unwrap().unwrap();
        assert_eq!(
            String::from_utf8(message.clone()).unwrap(),
            "n,,n=username,r=<<<client nonce>>>"
        );
        let message = server.process_message(&message, &env).unwrap();
        assert_eq!(
            String::from_utf8(message.clone()).unwrap(),
            "r=<<<client nonce>>><<<server nonce>>>,s=aGVsbG8=,i=4096"
        );
        let message = client.process_message(&message, &env).unwrap().unwrap();
        assert_eq!(String::from_utf8(message.clone()).unwrap(), "c=biws,r=<<<client nonce>>><<<server nonce>>>,p=621h6u6V3axb7mNYHNgTspTZ3SqILcxuJOsFu5wMjV8=");
        let message = server.process_message(&message, &env).unwrap();
        assert_eq!(
            String::from_utf8(message.clone()).unwrap(),
            "v=moj4kNnZKB3wjXZeQsKYI9luTTakwgH8r0NdGOjugRY="
        );
        assert!(client.process_message(&message, &env).unwrap().is_none());
        assert!(client.success());
        assert!(server.success());
    }
}