implement client.rs

This commit is contained in:
2025-12-13 12:26:03 -06:00
parent da8c57243d
commit 246fd97f5b
7 changed files with 200 additions and 257 deletions

12
Cargo.lock generated
View File

@@ -14,6 +14,17 @@ dependencies = [
"password-hash", "password-hash",
] ]
[[package]]
name = "async-trait"
version = "0.1.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "base16ct" name = "base16ct"
version = "0.2.0" version = "0.2.0"
@@ -322,6 +333,7 @@ checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"
name = "nkode-protocol" name = "nkode-protocol"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"async-trait",
"getset", "getset",
"opaque-ke", "opaque-ke",
"rand", "rand",

View File

@@ -9,4 +9,5 @@ rand = { version = "0.8.5", features = ["std"] }
sha2 = "0.10.9" sha2 = "0.10.9"
uuid = "1.19.0" uuid = "1.19.0"
getset = "0.1.6" getset = "0.1.6"
async-trait = "0.1.89"

View File

@@ -1,57 +1,46 @@
use opaque_ke::argon2::password_hash::rand_core::OsRng; use async_trait::async_trait;
use opaque_ke::{
CredentialFinalization, CredentialRequest, RegistrationRequest,
ClientLogin, ClientLoginFinishParameters, ClientRegistration,
ClientRegistrationFinishParameters
};
use uuid::Uuid; use uuid::Uuid;
use crate::protocol::{PasswordFile, KeyLoginPhaseISession, KeyRegisterSession, NKodeCipherSuite};
trait ServerConnectionRegister { use opaque_ke::rand::rngs::OsRng;
async fn start( use opaque_ke::{
&mut self, ClientLogin, ClientLoginFinishParameters,
identifier: &[u8], ClientRegistration, ClientRegistrationFinishParameters,
message: &RegistrationRequest<NKodeCipherSuite> CredentialFinalization, CredentialRequest, CredentialResponse,
) -> Result<KeyRegisterSession, String>; RegistrationRequest, RegistrationResponse,
};
async fn finish( use crate::models::{
&mut self, NKodeCipherSuite,
session_id: &Uuid, PasswordFile,
password_file: PasswordFile, KeyLoginSession,
) -> Result<(), String>; KeyRegisterSession,
};
#[derive(Debug)]
pub enum ClientAuthError {
Opaque(String),
Transport(String),
} }
trait ServerConnectionLogin { // --- Normalize auth inputs to (identifier, secret-bytes) ---
async fn start(
&mut self,
identifier: &[u8],
request_bytes: &CredentialRequest<NKodeCipherSuite>
) -> Result<KeyLoginPhaseISession, String>;
async fn finish( pub struct AuthenticationData {
&mut self, pub identifier: Vec<u8>,
session_id: &Uuid, pub secret: Vec<u8>,
message: &CredentialFinalization<NKodeCipherSuite>
) -> Result<(), String>;
}
struct AuthenticationData {
identifier: Vec<u8>,
secret: Vec<u8>,
} }
impl AuthenticationData { impl AuthenticationData {
fn from_secret_key(email: &String, secret_key: &[u8]) -> Self { pub fn from_secret_key(email: &str, secret_key: &[u8]) -> Self {
Self { Self {
identifier: email.as_bytes().to_vec(), identifier: email.as_bytes().to_vec(),
secret: secret_key.to_vec(), secret: secret_key.to_vec(),
} }
} }
fn from_code(email: &String, code: &[usize]) -> Self { pub fn from_code(email: &str, code: &[usize]) -> Self {
// fixed-width so it's stable across 32-bit vs 64-bit platforms
let mut secret = Vec::with_capacity(code.len() * 8); let mut secret = Vec::with_capacity(code.len() * 8);
for &n in code { for &n in code {
// fixed-width so it's stable across 32-bit vs 64-bit platforms
secret.extend_from_slice(&(n as u64).to_le_bytes()); secret.extend_from_slice(&(n as u64).to_le_bytes());
} }
Self { Self {
@@ -61,32 +50,125 @@ impl AuthenticationData {
} }
} }
struct OpaqueAuthentication; // --- Small adapter traits so server can return any “session wrapper” type ---
pub trait RegStartSession {
fn session_id(&self) -> &Uuid;
fn response(&self) -> &RegistrationResponse<NKodeCipherSuite>;
}
pub trait LoginStartSession {
fn session_id(&self) -> &Uuid;
fn response(&self) -> &CredentialResponse<NKodeCipherSuite>;
}
// If your protocol types already have these methods, just implement the traits:
impl RegStartSession for KeyRegisterSession {
fn session_id(&self) -> &Uuid { self.session_id() }
fn response(&self) -> &RegistrationResponse<NKodeCipherSuite> { self.response() }
}
impl LoginStartSession for KeyLoginSession {
fn session_id(&self) -> &Uuid { self.session_id() }
fn response(&self) -> &CredentialResponse<NKodeCipherSuite> { self.response() }
}
// --- Server connection traits: generic over returned session wrapper types ---
#[async_trait]
pub trait ServerConnectionRegister {
type Start: RegStartSession + Send;
async fn start(
&mut self,
identifier: &[u8],
message: &RegistrationRequest<NKodeCipherSuite>,
) -> Result<Self::Start, ClientAuthError>;
async fn finish(
&mut self,
session_id: &Uuid,
password_file: PasswordFile,
) -> Result<(), ClientAuthError>;
}
#[async_trait]
pub trait ServerConnectionLogin {
type Start: LoginStartSession + Send;
async fn start(
&mut self,
identifier: &[u8],
request: &CredentialRequest<NKodeCipherSuite>,
) -> Result<Self::Start, ClientAuthError>;
async fn finish(
&mut self,
session_id: &Uuid,
message: &CredentialFinalization<NKodeCipherSuite>,
) -> Result<(), ClientAuthError>;
}
// --- OPAQUE client driver ---
pub struct OpaqueAuthentication;
impl OpaqueAuthentication { impl OpaqueAuthentication {
async fn register( pub async fn register(
key_data: &AuthenticationData, auth: &AuthenticationData,
server: &mut impl ServerConnectionRegister server: &mut impl ServerConnectionRegister,
) -> Result<(), String> ) -> Result<(), ClientAuthError> {
{ let mut rng = OsRng;
let mut client_rng = OsRng; let start = ClientRegistration::<NKodeCipherSuite>::start(&mut rng, &auth.secret)
let client_reg_start = ClientRegistration::<NKodeCipherSuite>::start(&mut client_rng, &key_data.secret).expect("error starting registration"); .map_err(|e| ClientAuthError::Opaque(format!("client reg start: {e:?}")))?;
let server_response = server.start(&key_data.identifier, &client_reg_start.message).await.expect("error getting server response"); let server_start = server
let client_finish = client_reg_start.state.finish(&mut client_rng, &key_data.secret, server_response.response().clone(), ClientRegistrationFinishParameters::default()).expect(""); .start(&auth.identifier, &start.message)
server.finish(server_response.session_id(), client_finish.message.serialize()).await.expect("server to finish secret reg without error"); .await
.map_err(|e| ClientAuthError::Transport(format!("server reg start: {e:?}")))?;
let server_msg = server_start.response().clone();
let finish = start
.state
.finish(
&mut rng,
&auth.secret,
server_msg,
ClientRegistrationFinishParameters::default(),
)
.map_err(|e| ClientAuthError::Opaque(format!("client reg finish: {e:?}")))?;
// Assuming PasswordFile is Vec<u8> (serialized server-side password file)
let password_file: PasswordFile = finish.message.serialize();
server
.finish(server_start.session_id(), password_file)
.await
.map_err(|e| ClientAuthError::Transport(format!("server reg finish: {e:?}")))?;
Ok(()) Ok(())
} }
async fn login( pub async fn login(
auth_data: &AuthenticationData, auth: &AuthenticationData,
server: &mut impl ServerConnectionLogin server: &mut impl ServerConnectionLogin,
) -> Result<Vec<u8>, String> ) -> Result<Vec<u8>, ClientAuthError> {
{ let mut rng = OsRng;
let mut client_rng = OsRng; let start = ClientLogin::<NKodeCipherSuite>::start(&mut rng, &auth.secret)
let client_start = ClientLogin::<NKodeCipherSuite>::start(&mut client_rng, &auth_data.secret).expect("client secret key login to start result"); .map_err(|e| ClientAuthError::Opaque(format!("client login start: {e:?}")))?;
let server_response = server.start(&auth_data.identifier, &client_start.message).await.expect("server secret key login start response"); let server_start = server
let client_finish = client_start.state.finish(&mut client_rng, &auth_data.secret, server_response.response().clone(), ClientLoginFinishParameters::default()).expect(""); .start(&auth.identifier, &start.message)
server.finish(server_response.session_id(), &client_finish.message).await.expect("server secret key login to finish"); .await
Ok(client_finish.session_key.to_vec()) .map_err(|e| ClientAuthError::Transport(format!("server login start: {e:?}")))?;
let server_msg = server_start.response().clone();
let finish = start
.state
.finish(
&mut rng,
&auth.secret,
server_msg,
ClientLoginFinishParameters::default(),
)
.map_err(|e| ClientAuthError::Opaque(format!("client login finish: {e:?}")))?;
server
.finish(server_start.session_id(), &finish.message)
.await
.map_err(|e| ClientAuthError::Transport(format!("server login finish: {e:?}")))?;
Ok(finish.session_key.to_vec())
} }
} }

View File

@@ -1,3 +1,3 @@
mod protocol; mod models;
mod client; mod client;
mod server; mod server;

44
src/models.rs Normal file
View File

@@ -0,0 +1,44 @@
use opaque_ke::{RegistrationResponse, Ristretto255, TripleDh, ServerSetup, CredentialResponse, RegistrationUploadLen};
use opaque_ke::keypair::{OprfSeed, PrivateKey};
use sha2::Sha512;
use opaque_ke::CipherSuite;
use opaque_ke::argon2::Argon2;
use opaque_ke::generic_array::GenericArray;
use uuid::Uuid;
use getset::Getters;
pub const NONCE_SIZE: usize = 12;
pub const SESSION_KEY_SIZE: usize = 32;
pub const SECRET_KEY_SIZE: usize = 16;
pub struct NKodeCipherSuite;
impl CipherSuite for NKodeCipherSuite {
type OprfCs = Ristretto255;
type KeyExchange = TripleDh<Ristretto255, Sha512>;
type Ksf = Argon2<'static>;
}
pub type NKodeServerSetup = ServerSetup<NKodeCipherSuite, PrivateKey<Ristretto255>, OprfSeed<Sha512>>;
#[derive(Debug, Clone, PartialEq, Eq, Getters)]
pub struct RegisterSession {
#[get = "pub"]
response: RegistrationResponse<NKodeCipherSuite>,
#[get = "pub"]
session_id: Uuid
}
pub type PasswordFile = GenericArray<u8, RegistrationUploadLen<NKodeCipherSuite>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginSession {
pub response: CredentialResponse<NKodeCipherSuite>,
pub session_id: Uuid
}
pub type KeyRegisterSession = RegisterSession;
pub type KeyLoginSession = LoginSession;

View File

@@ -1,196 +0,0 @@
use opaque_ke::{CredentialFinalization, CredentialRequest, RegistrationRequest, RegistrationResponse, Ristretto255, TripleDh, ServerLogin, ServerLoginParameters, ServerLoginStartResult, ServerRegistration, ServerSetup, ClientRegistrationStartResult, ClientLogin, ClientLoginFinishParameters, ClientLoginFinishResult, ClientLoginStartResult, ClientRegistration, ClientRegistrationFinishParameters, CredentialResponse, RegistrationUploadLen, ServerLoginFinishResult};
use opaque_ke::errors::ProtocolError;
use opaque_ke::keypair::{OprfSeed, PrivateKey};
use sha2::Sha512;
use opaque_ke::CipherSuite;
use opaque_ke::argon2::Argon2;
use opaque_ke::generic_array::GenericArray;
use uuid::Uuid;
use opaque_ke::rand::rngs::OsRng;
use std::marker::PhantomData;
use getset::Getters;
pub const NONCE_SIZE: usize = 12;
pub const SESSION_KEY_SIZE: usize = 32;
pub const SECRET_KEY_SIZE: usize = 16;
pub struct NKodeCipherSuite;
impl CipherSuite for NKodeCipherSuite {
type OprfCs = Ristretto255;
type KeyExchange = TripleDh<Ristretto255, Sha512>;
type Ksf = Argon2<'static>;
}
pub type NKodeServerSetup = ServerSetup<NKodeCipherSuite, PrivateKey<Ristretto255>, OprfSeed<Sha512>>;
#[derive(Debug, Clone, PartialEq, Eq, Getters)]
pub struct RegisterSession {
#[get = "pub"]
response: RegistrationResponse<NKodeCipherSuite>,
#[get = "pub"]
session_id: Uuid
}
pub type PasswordFile = GenericArray<u8, RegistrationUploadLen<NKodeCipherSuite>>;
pub async fn register_secret_key<R,S>(
email: &String,
key: &[u8; SECRET_KEY_SIZE],
server: &mut NKodeServer<KeyRegister, R, S>
) -> Result<(),String>
where
R: Repo,
S: Sessions
{
let mut client_rng = OsRng;
let client_reg_start = ClientRegistration::<NKodeCipherSuite>::start(&mut client_rng, key).expect("error starting registration");
let server_response = server.start(email, &client_reg_start.message).await.expect("error getting server response");
let client_finish = client_reg_start.state.finish(&mut client_rng, key, server_response.response, ClientRegistrationFinishParameters::default()).expect("");
server.finish(&server_response.session_id, &client_finish.message.serialize()).await.expect("server to finish secret reg without error");
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginSession {
pub response: CredentialResponse<NKodeCipherSuite>,
pub session_id: Uuid
}
pub async fn login_secret_key<R, S>(email: &String, key: &[u8; SECRET_KEY_SIZE], server: &mut NKodeServer<KeyLoginI, R, S>) -> Result<Vec<u8>, String>
where
R: Repo,
S: Sessions
{
let mut client_rng = OsRng;
let client_start = ClientLogin::<NKodeCipherSuite>::start(&mut client_rng, key).expect("client secret key login to start result");
let server_response = server.start(email, client_start.message).await.expect("server secret key login start response");
let client_finish = client_start.state.finish(&mut client_rng, key,server_response.response,ClientLoginFinishParameters::default()).expect("");
server.finish(&server_response.session_id, client_finish.message).await.expect("server secret key login to finish");
Ok(client_finish.session_key.to_vec())
}
pub trait Repo {}
pub trait Sessions {}
pub struct NKodeServer<State, R: Repo, S: Sessions> {
server_setup: NKodeServerSetup,
repo: R,
session: S,
_state: PhantomData<State>
}
pub type KeyRegisterSession = RegisterSession;
pub struct KeyRegister;
pub struct KeyLoginI;
pub struct CodeRegister;
impl<R, S> NKodeServer<KeyRegister, R, S>
where
R: Repo,
S: Sessions
{
pub fn new(server_setup: NKodeServerSetup, repo: R, sessions: S) -> Self {
todo!()
}
pub async fn start(
&mut self,
email: &String,
message: &RegistrationRequest<NKodeCipherSuite>
) -> Result<KeyRegisterSession, ProtocolError> {
todo!()
}
pub async fn finish(
&mut self,
session_id: &Uuid,
password_file: &PasswordFile
) -> Result<NKodeServer<KeyLoginI, R, S>, ProtocolError> {
todo!()
}
}
pub type KeyLoginPhaseISession = LoginSession;
impl<R,S> NKodeServer<KeyLoginI, R, S>
where
R: Repo,
S: Sessions
{
pub async fn start(
&mut self,
email: &String,
request_bytes:CredentialRequest<NKodeCipherSuite>
) -> Result<KeyLoginPhaseISession, ProtocolError> {
todo!()
}
pub async fn finish(
&mut self,
session_id: &Uuid,
message: CredentialFinalization<NKodeCipherSuite>
) -> Result<NKodeServer<CodeRegister, R, S>, ProtocolError> {
todo!()
}
}
pub type CodeRegisterSession = RegisterSession;
pub struct CodeLogin;
impl<R, S> NKodeServer<CodeRegister, R, S>
where
R: Repo,
S: Sessions
{
pub fn new(server_setup: NKodeServerSetup) -> Self {
todo!()
}
pub async fn start(
&mut self,
email: &String,
message: &RegistrationRequest<NKodeCipherSuite>
) -> Result<CodeRegisterSession, ProtocolError> {
todo!()
}
pub async fn finish(
&mut self,
session_id: &Uuid,
password_file: &PasswordFile) -> Result<NKodeServer<CodeLogin, R, S>, ProtocolError> {
todo!()
}
}
pub type CodeLoginSession = LoginSession;
impl <R, S> NKodeServer<CodeLogin, R, S>
where
R: Repo,
S: Sessions
{
pub async fn start(
&mut self,
email: &String,
request_bytes:CredentialRequest<NKodeCipherSuite>
) -> Result<CodeLoginSession, ProtocolError> {
todo!()
}
pub async fn finish(
&mut self,
session_id: &Uuid,
message:CredentialFinalization<NKodeCipherSuite>
) -> Result<LoggedIn, ProtocolError> {
todo!()
}
}
pub struct LoggedIn {
session_key: Vec<u8>,
session_id: Uuid,
}

View File

@@ -11,7 +11,7 @@ use opaque_ke::{
use uuid::Uuid; use uuid::Uuid;
// --- Your crate types (as referenced in your snippet) --- // --- Your crate types (as referenced in your snippet) ---
use crate::protocol::{LoginSession, NKodeCipherSuite, NKodeServerSetup, PasswordFile}; use crate::models::{LoginSession, NKodeCipherSuite, NKodeServerSetup, PasswordFile};
// ---------------- Errors ---------------- // ---------------- Errors ----------------