use bytes::{Buf, Bytes, BytesMut};
use super::property::{self, PROP_ID_LEN, PropertyId, properties_encoded_len, write_properties_len};
use crate::{DecodeError, EncodeError, PacketType, primitives};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum AuthStatus {
Success = 0x00,
Continue = 0x18,
ReAuthenticate = 0x19,
}
impl TryFrom<u8> for AuthStatus {
type Error = DecodeError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(Self::Success),
0x18 => Ok(Self::Continue),
0x19 => Ok(Self::ReAuthenticate),
_ => Err(DecodeError::InvalidReasonCode {
packet_type: PacketType::Auth,
value,
}),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AuthProperties {
pub authentication_method: Option<String>,
pub authentication_data: Option<Bytes>,
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
impl AuthProperties {
fn encoded_len(&self) -> usize {
let mut len = 0;
if let Some(ref s) = self.authentication_method {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if let Some(ref d) = self.authentication_data {
len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
}
if let Some(ref s) = self.reason_string {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
for (k, v) in &self.user_properties {
len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
}
len
}
fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
let props_len = self.encoded_len();
write_properties_len(props_len, buf);
if let Some(ref s) = self.authentication_method {
primitives::write_u8(PropertyId::AuthenticationMethod as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(ref d) = self.authentication_data {
primitives::write_u8(PropertyId::AuthenticationData as u8, buf);
primitives::write_binary(d, buf)?;
}
if let Some(ref s) = self.reason_string {
primitives::write_u8(PropertyId::ReasonString as u8, buf);
primitives::write_string(s, buf)?;
}
for (k, v) in &self.user_properties {
primitives::write_u8(PropertyId::UserProperty as u8, buf);
primitives::write_string_pair(k, v, buf)?;
}
Ok(())
}
fn decode(mut buf: Bytes) -> Result<Self, DecodeError> {
let mut props = Self::default();
while buf.has_remaining() {
let id_byte = primitives::read_u8(&mut buf)?;
let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
packet_type: PacketType::Auth,
id: id_byte,
})?;
match id {
PropertyId::AuthenticationMethod => {
if props.authentication_method.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.authentication_method = Some(primitives::read_string(&mut buf)?);
}
PropertyId::AuthenticationData => {
if props.authentication_data.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.authentication_data = Some(primitives::read_binary(&mut buf)?);
}
PropertyId::ReasonString => {
if props.reason_string.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.reason_string = Some(primitives::read_string(&mut buf)?);
}
PropertyId::UserProperty => {
props.user_properties.push(primitives::read_string_pair(&mut buf)?);
}
_ => {
return Err(DecodeError::InvalidProperty {
packet_type: PacketType::Auth,
id: id_byte,
});
}
}
}
Ok(props)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Auth {
pub status: AuthStatus,
pub properties: AuthProperties,
}
impl Auth {
const FLAGS: u8 = 0b0000;
pub(super) fn flags(&self) -> u8 {
Self::FLAGS
}
pub(super) fn encoded_body_len(&self) -> usize {
let props_body_len = self.properties.encoded_len();
if self.status as u8 == 0x00 && props_body_len == 0 {
return 0;
}
1 + properties_encoded_len(props_body_len)
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
let props_body_len = self.properties.encoded_len();
if self.status as u8 == 0x00 && props_body_len == 0 {
return Ok(());
}
primitives::write_u8(self.status as u8, buf);
self.properties.encode(buf)?;
Ok(())
}
pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
if header_flags != Self::FLAGS {
return Err(DecodeError::InvalidFlags {
packet_type: PacketType::Auth,
flags: header_flags,
});
}
if buf.is_empty() {
return Ok(Self {
status: AuthStatus::Success,
properties: AuthProperties::default(),
});
}
let reason_byte = primitives::read_u8(&mut buf)?;
let status = AuthStatus::try_from(reason_byte)?;
let properties = if buf.has_remaining() {
let props_buf = property::read_properties_bytes(&mut buf)?;
AuthProperties::decode(props_buf)?
} else {
AuthProperties::default()
};
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(Self { status, properties })
}
}
#[cfg(test)]
mod tests {
use bytes::{Bytes, BytesMut};
use super::*;
use crate::v5::Packet;
use crate::{DecodeError, PacketType};
fn roundtrip(packet: Packet) -> Packet {
let mut buf = BytesMut::new();
packet.encode(&mut buf).unwrap();
Packet::decode(&mut buf).unwrap().unwrap()
}
#[test]
fn auth_abbreviated_success() {
let pkt = Packet::Auth(Auth {
status: AuthStatus::Success,
properties: AuthProperties::default(),
});
let mut buf = BytesMut::new();
pkt.encode(&mut buf).unwrap();
assert_eq!(&buf[..], &[0xF0, 0x00]); assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn auth_continue_with_properties() {
let pkt = Packet::Auth(Auth {
status: AuthStatus::Continue,
properties: AuthProperties {
authentication_method: Some("SCRAM-SHA-256".to_owned()),
authentication_data: Some(Bytes::from_static(b"client-first")),
reason_string: None,
user_properties: vec![],
},
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn auth_reauthenticate() {
let pkt = Packet::Auth(Auth {
status: AuthStatus::ReAuthenticate,
properties: AuthProperties {
authentication_method: Some("PLAIN".to_owned()),
authentication_data: Some(Bytes::from_static(b"creds")),
reason_string: Some("re-auth needed".to_owned()),
user_properties: vec![("k".to_owned(), "v".to_owned())],
},
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn auth_invalid_status() {
let buf = Bytes::from_static(&[0x05, 0x00]); assert_eq!(
Auth::decode_body(0x00, buf),
Err(DecodeError::InvalidReasonCode {
packet_type: PacketType::Auth,
value: 0x05,
})
);
}
#[test]
fn auth_invalid_flags() {
assert_eq!(
Auth::decode_body(0x01, Bytes::new()),
Err(DecodeError::InvalidFlags {
packet_type: PacketType::Auth,
flags: 0x01,
})
);
}
#[test]
fn auth_empty_body_decodes_as_success() {
let result = Auth::decode_body(0x00, Bytes::new()).unwrap();
assert_eq!(result.status, AuthStatus::Success);
assert_eq!(result.properties, AuthProperties::default());
}
}