use futures_util::{SinkExt, StreamExt};
use tinyscram::ServerSession;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use crate::errors;
use crate::proto::backend::BackendMessage;
use crate::proto::codec::FrontendCodec;
use crate::proto::frontend::FrontendMessage;
use super::verifier::ScramVerifier;
pub async fn authenticate(
client: &mut Framed<TcpStream, FrontendCodec>,
verifier: ScramVerifier,
) -> Result<(), errors::AuthError> {
let mut scram = ServerSession::new(verifier);
client
.send(BackendMessage::AuthenticationSasl {
mechanisms: vec!["SCRAM-SHA-256".into()],
})
.await?;
let initial_data = match client.next().await.transpose()? {
Some(FrontendMessage::PasswordMessage(data)) => data,
Some(other) => {
return Err(errors::AuthError::Protocol(format!(
"expected SASLInitialResponse, got {other:?}"
)));
}
None => {
return Err(errors::AuthError::Protocol(
"client disconnected during SASL".into(),
));
}
};
let (mechanism, client_first) = parse_sasl_initial_response(&initial_data)?;
if mechanism != "SCRAM-SHA-256" {
return Err(errors::AuthError::Protocol(format!(
"unsupported SASL mechanism: {mechanism:?}"
)));
}
let server_first = scram.handle_client_first(client_first).map_err(map_scram)?;
client
.send(BackendMessage::AuthenticationSaslContinue { data: server_first })
.await?;
let final_data = match client.next().await.transpose()? {
Some(FrontendMessage::PasswordMessage(data)) => data,
Some(other) => {
return Err(errors::AuthError::Protocol(format!(
"expected SASLResponse, got {other:?}"
)));
}
None => {
return Err(errors::AuthError::Protocol(
"client disconnected during SASL".into(),
));
}
};
let server_final = scram.handle_client_final(&final_data).map_err(map_scram)?;
client
.feed(BackendMessage::AuthenticationSaslFinal { data: server_final })
.await?;
client.send(BackendMessage::AuthenticationOk).await?;
Ok(())
}
pub fn parse_sasl_initial_response(data: &[u8]) -> Result<(&str, &[u8]), errors::AuthError> {
let nul = data
.iter()
.position(|&b| b == 0)
.ok_or_else(|| errors::AuthError::Protocol("missing null in SASLInitialResponse".into()))?;
let mechanism = std::str::from_utf8(&data[..nul])
.map_err(|_| errors::AuthError::Protocol("invalid UTF-8 in mechanism name".into()))?;
let rest = &data[nul + 1..];
if rest.len() < 4 {
return Err(errors::AuthError::Protocol(
"truncated SASLInitialResponse length".into(),
));
}
let len = i32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]);
let response = if len < 0 {
&[]
} else {
let len = len as usize;
if rest.len() < 4 + len {
return Err(errors::AuthError::Protocol(
"truncated SASLInitialResponse data".into(),
));
}
&rest[4..4 + len]
};
Ok((mechanism, response))
}
pub(crate) fn map_scram(e: tinyscram::Error) -> errors::AuthError {
match e {
tinyscram::Error::InvalidProof => errors::AuthError::InvalidCredentials,
other => errors::AuthError::Protocol(format!("scram: {other}")),
}
}