Line data Source code
1 : //! Definitions for SASL messages.
2 :
3 : use crate::parse::{split_at_const, split_cstr};
4 : use pq_proto::{BeAuthenticationSaslMessage, BeMessage};
5 :
6 : /// SASL-specific payload of [`PasswordMessage`](pq_proto::FeMessage::PasswordMessage).
7 0 : #[derive(Debug)]
8 : pub struct FirstMessage<'a> {
9 : /// Authentication method, e.g. `"SCRAM-SHA-256"`.
10 : pub method: &'a str,
11 : /// Initial client message.
12 : pub message: &'a str,
13 : }
14 :
15 : impl<'a> FirstMessage<'a> {
16 : // NB: FromStr doesn't work with lifetimes
17 61 : pub fn parse(bytes: &'a [u8]) -> Option<Self> {
18 61 : let (method_cstr, tail) = split_cstr(bytes)?;
19 61 : let method = method_cstr.to_str().ok()?;
20 :
21 61 : let (len_bytes, bytes) = split_at_const(tail)?;
22 61 : let len = u32::from_be_bytes(*len_bytes) as usize;
23 61 : if len != bytes.len() {
24 0 : return None;
25 61 : }
26 :
27 61 : let message = std::str::from_utf8(bytes).ok()?;
28 61 : Some(Self { method, message })
29 61 : }
30 : }
31 :
32 : /// A single SASL message.
33 : /// This struct is deliberately decoupled from lower-level
34 : /// [`BeAuthenticationSaslMessage`].
35 0 : #[derive(Debug)]
36 : pub(super) enum ServerMessage<T> {
37 : /// We expect to see more steps.
38 : Continue(T),
39 : /// This is the final step.
40 : Final(T),
41 : }
42 :
43 : impl<'a> ServerMessage<&'a str> {
44 101 : pub(super) fn to_reply(&self) -> BeMessage<'a> {
45 101 : use BeAuthenticationSaslMessage::*;
46 101 : BeMessage::AuthenticationSasl(match self {
47 57 : ServerMessage::Continue(s) => Continue(s.as_bytes()),
48 44 : ServerMessage::Final(s) => Final(s.as_bytes()),
49 : })
50 101 : }
51 : }
52 :
53 : #[cfg(test)]
54 : mod tests {
55 : use super::*;
56 :
57 2 : #[test]
58 2 : fn parse_sasl_first_message() {
59 2 : let proto = "SCRAM-SHA-256";
60 2 : let sasl = "n,,n=,r=KHQ2Gjc7NptyB8aov5/TnUy4";
61 2 : let sasl_len = (sasl.len() as u32).to_be_bytes();
62 2 : let bytes = [proto.as_bytes(), &[0], sasl_len.as_ref(), sasl.as_bytes()].concat();
63 2 :
64 2 : let password = FirstMessage::parse(&bytes).unwrap();
65 2 : assert_eq!(password.method, proto);
66 2 : assert_eq!(password.message, sasl);
67 2 : }
68 : }
|