implement noise auth basic

This commit is contained in:
mbecker20
2025-09-20 15:44:50 -07:00
parent 01de8c4a9b
commit 3d455f5142
16 changed files with 563 additions and 67 deletions

View File

@@ -1,5 +1,6 @@
use anyhow::{Context, anyhow};
use bytes::Bytes;
use rand::RngCore;
use tracing::{info, warn};
use crate::{
@@ -13,10 +14,50 @@ pub enum AuthType {
Noise = 1,
}
pub async fn handle_server_side_login(
socket: &mut impl Websocket,
validate_credentials: impl Fn(&[u8]) -> bool,
) -> anyhow::Result<()> {
// Server generates random nonce and sends to client
let nonce = nonce();
socket.send(Bytes::copy_from_slice(&nonce)).await?;
let credentials = match socket.recv().await? {
WebsocketMessage::Binary(bytes) => bytes,
WebsocketMessage::Close(frame) => {
return Err(anyhow!(
"Websocket close frame received during login | frame: {frame:?}"
));
}
WebsocketMessage::Closed => {
return Err(anyhow!("Websocket closed during login"));
}
};
if validate_credentials(&credentials) {
// Send login confirmation
// TODO: remove / edit logs
info!("Client logged in");
socket.send(MessageState::Successful.into()).await?;
return Ok(());
} else {
// Send login failure
warn!("Client failed to log in");
socket.send(MessageState::Failed.into()).await?;
let _ = socket.close(None).await;
return Err(anyhow!("Received invalid credentials"));
}
}
pub async fn handle_client_side_login(
socket: &mut impl Websocket,
credentials: Bytes,
) -> anyhow::Result<()> {
let nonce = socket
.recv_bytes()
.await
.context("Failed to receive connection nonce")?;
socket
.send(credentials)
.await
@@ -44,32 +85,8 @@ pub async fn handle_client_side_login(
}
}
pub async fn handle_server_side_login(
socket: &mut impl Websocket,
validate_credentials: impl Fn(&[u8]) -> bool,
) -> anyhow::Result<()> {
let credentials = match socket.recv().await? {
WebsocketMessage::Binary(bytes) => bytes,
WebsocketMessage::Close(frame) => {
return Err(anyhow!(
"Websocket close frame received during login | frame: {frame:?}"
));
}
WebsocketMessage::Closed => {
return Err(anyhow!("Websocket closed during login"));
}
};
if validate_credentials(&credentials) {
// Send login confirmation
// TODO: remove / edit logs
info!("Client logged in");
socket.send(MessageState::Successful.into()).await?;
return Ok(());
} else {
// Send login failure
warn!("Client failed to log in");
socket.send(MessageState::Failed.into()).await?;
let _ = socket.close(None).await;
return Err(anyhow!("Received invalid credentials"));
}
fn nonce() -> [u8; 32] {
let mut out = [0u8; 32];
rand::rng().fill_bytes(&mut out);
out
}