Update opaque and implement it without DB
This commit is contained in:
committed by
nitnelave
parent
f12abb35d3
commit
8b73de0df7
@@ -9,6 +9,12 @@ pub enum DomainError {
|
||||
DatabaseError(#[from] sqlx::Error),
|
||||
#[error("Authentication protocol error for `{0}`")]
|
||||
AuthenticationProtocolError(#[from] lldap_model::opaque::AuthenticationError),
|
||||
#[error("Unknown crypto error: `{0}`")]
|
||||
UnknownCryptoError(#[from] orion::errors::UnknownCryptoError),
|
||||
#[error("Binary serialization error: `{0}`")]
|
||||
BinarySerializationError(#[from] bincode::Error),
|
||||
#[error("Invalid base64: `{0}`")]
|
||||
Base64DecodeError(#[from] base64::DecodeError),
|
||||
#[error("Internal error: `{0}`")]
|
||||
InternalError(String),
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ impl SqlBackendHandler {
|
||||
|
||||
pub fn get_password_file(
|
||||
clear_password: &str,
|
||||
server_public_key: &opaque::PublicKey,
|
||||
server_setup: &opaque::server::ServerSetup,
|
||||
username: &str,
|
||||
) -> Result<opaque::server::ServerRegistration> {
|
||||
use opaque::{client, server};
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
@@ -30,9 +31,9 @@ pub fn get_password_file(
|
||||
client::registration::start_registration(clear_password, &mut rng)?;
|
||||
|
||||
let server_register_start_result = server::registration::start_registration(
|
||||
&mut rng,
|
||||
server_setup,
|
||||
client_register_start_result.message,
|
||||
server_public_key,
|
||||
username,
|
||||
)?;
|
||||
|
||||
let client_registration_result = client::registration::finish_registration(
|
||||
@@ -42,9 +43,8 @@ pub fn get_password_file(
|
||||
)?;
|
||||
|
||||
Ok(server::registration::get_password_file(
|
||||
server_register_start_result.state,
|
||||
client_registration_result.message,
|
||||
)?)
|
||||
))
|
||||
}
|
||||
|
||||
fn get_filter_expr(filter: RequestFilter) -> SimpleExpr {
|
||||
@@ -187,7 +187,7 @@ impl BackendHandler for SqlBackendHandler {
|
||||
Users::CreationDate,
|
||||
];
|
||||
let mut values = vec![
|
||||
request.user_id.into(),
|
||||
request.user_id.clone().into(),
|
||||
request.email.into(),
|
||||
request.display_name.map(Into::into).unwrap_or(Value::Null),
|
||||
request.first_name.map(Into::into).unwrap_or(Value::Null),
|
||||
@@ -197,7 +197,7 @@ impl BackendHandler for SqlBackendHandler {
|
||||
if let Some(pass) = request.password {
|
||||
columns.push(Users::PasswordHash);
|
||||
values.push(
|
||||
get_password_file(&pass, self.config.get_server_keys().public())?
|
||||
get_password_file(&pass, self.config.get_server_setup(), &request.user_id)?
|
||||
.serialize()
|
||||
.into(),
|
||||
);
|
||||
|
||||
@@ -5,25 +5,16 @@ use super::{
|
||||
use async_trait::async_trait;
|
||||
use lldap_model::{opaque, BindRequest};
|
||||
use log::*;
|
||||
use rand::{CryptoRng, RngCore};
|
||||
use sea_query::{Expr, Iden, Query};
|
||||
use sqlx::Row;
|
||||
|
||||
type SqlOpaqueHandler = SqlBackendHandler;
|
||||
|
||||
fn generate_random_id<R: RngCore + CryptoRng>(rng: &mut R) -> String {
|
||||
use rand::{distributions::Alphanumeric, Rng};
|
||||
std::iter::repeat(())
|
||||
.map(|()| rng.sample(Alphanumeric))
|
||||
.map(char::from)
|
||||
.take(32)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn passwords_match(
|
||||
password_file_bytes: &[u8],
|
||||
clear_password: &str,
|
||||
server_private_key: &opaque::PrivateKey,
|
||||
server_setup: &opaque::server::ServerSetup,
|
||||
username: &str,
|
||||
) -> Result<()> {
|
||||
use opaque::{client, server};
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
@@ -33,9 +24,10 @@ fn passwords_match(
|
||||
.map_err(opaque::AuthenticationError::ProtocolError)?;
|
||||
let server_login_start_result = server::login::start_login(
|
||||
&mut rng,
|
||||
password_file,
|
||||
server_private_key,
|
||||
server_setup,
|
||||
Some(password_file),
|
||||
client_login_start_result.message,
|
||||
username,
|
||||
)?;
|
||||
client::login::finish_login(
|
||||
client_login_start_result.state,
|
||||
@@ -44,6 +36,40 @@ fn passwords_match(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl SqlBackendHandler {
|
||||
fn get_orion_secret_key(&self) -> Result<orion::aead::SecretKey> {
|
||||
Ok(orion::aead::SecretKey::from_slice(
|
||||
self.config.get_server_keys().private(),
|
||||
)?)
|
||||
}
|
||||
|
||||
async fn get_password_file_for_user(
|
||||
&self,
|
||||
username: &str,
|
||||
) -> Result<Option<opaque::server::ServerRegistration>> {
|
||||
// Fetch the previously registered password file from the DB.
|
||||
let password_file_bytes = {
|
||||
let query = Query::select()
|
||||
.column(Users::PasswordHash)
|
||||
.from(Users::Table)
|
||||
.and_where(Expr::col(Users::UserId).eq(username))
|
||||
.to_string(DbQueryBuilder {});
|
||||
if let Some(row) = sqlx::query(&query).fetch_optional(&self.sql_pool).await? {
|
||||
row.get::<Option<Vec<u8>>, _>(&*Users::PasswordHash.to_string())
|
||||
// If no password, always fail.
|
||||
.ok_or_else(|| DomainError::AuthenticationError(username.to_string()))?
|
||||
} else {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
opaque::server::ServerRegistration::deserialize(&password_file_bytes)
|
||||
.map(Option::Some)
|
||||
.map_err(|_| {
|
||||
DomainError::InternalError(format!("Corrupted password file for {}", username))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl LoginHandler for SqlBackendHandler {
|
||||
async fn bind(&self, request: BindRequest) -> Result<()> {
|
||||
@@ -67,7 +93,8 @@ impl LoginHandler for SqlBackendHandler {
|
||||
if let Err(e) = passwords_match(
|
||||
&password_hash,
|
||||
&request.password,
|
||||
self.config.get_server_keys().private(),
|
||||
self.config.get_server_setup(),
|
||||
&request.name,
|
||||
) {
|
||||
debug!(r#"Invalid password for "{}": {}"#, request.name, e);
|
||||
} else {
|
||||
@@ -89,99 +116,44 @@ impl OpaqueHandler for SqlOpaqueHandler {
|
||||
&self,
|
||||
request: login::ClientLoginStartRequest,
|
||||
) -> Result<login::ServerLoginStartResponse> {
|
||||
// Fetch the previously registered password file from the DB.
|
||||
let password_file_bytes = {
|
||||
let query = Query::select()
|
||||
.column(Users::PasswordHash)
|
||||
.from(Users::Table)
|
||||
.and_where(Expr::col(Users::UserId).eq(request.username.as_str()))
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&query)
|
||||
.fetch_one(&self.sql_pool)
|
||||
.await?
|
||||
.get::<Option<Vec<u8>>, _>(&*Users::PasswordHash.to_string())
|
||||
// If no password, always fail.
|
||||
.ok_or_else(|| DomainError::AuthenticationError(request.username.clone()))?
|
||||
};
|
||||
let password_file = opaque::server::ServerRegistration::deserialize(&password_file_bytes)
|
||||
.map_err(|_| {
|
||||
DomainError::InternalError(format!("Corrupted password file for {}", request.username))
|
||||
})?;
|
||||
let maybe_password_file = self.get_password_file_for_user(&request.username).await?;
|
||||
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
let start_response = opaque::server::login::start_login(
|
||||
&mut rng,
|
||||
password_file,
|
||||
self.config.get_server_keys().private(),
|
||||
self.config.get_server_setup(),
|
||||
maybe_password_file,
|
||||
request.login_start_request,
|
||||
&request.username,
|
||||
)?;
|
||||
let login_attempt_id = generate_random_id(&mut rng);
|
||||
|
||||
{
|
||||
// Insert the current login attempt in the DB.
|
||||
let query = Query::insert()
|
||||
.into_table(LoginAttempts::Table)
|
||||
.columns(vec![
|
||||
LoginAttempts::RandomId,
|
||||
LoginAttempts::UserId,
|
||||
LoginAttempts::ServerLoginData,
|
||||
LoginAttempts::Timestamp,
|
||||
])
|
||||
.values_panic(vec![
|
||||
login_attempt_id.as_str().into(),
|
||||
request.username.as_str().into(),
|
||||
start_response.state.serialize().into(),
|
||||
chrono::Utc::now().naive_utc().into(),
|
||||
])
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&query).execute(&self.sql_pool).await?;
|
||||
}
|
||||
let secret_key = self.get_orion_secret_key()?;
|
||||
let server_data = login::ServerData {
|
||||
username: request.username,
|
||||
server_login: start_response.state,
|
||||
};
|
||||
let encrypted_state = orion::aead::seal(&secret_key, &bincode::serialize(&server_data)?)?;
|
||||
|
||||
Ok(login::ServerLoginStartResponse {
|
||||
login_key: login_attempt_id,
|
||||
server_data: base64::encode(&encrypted_state),
|
||||
credential_response: start_response.message,
|
||||
})
|
||||
}
|
||||
|
||||
async fn login_finish(&self, request: login::ClientLoginFinishRequest) -> Result<String> {
|
||||
// Fetch the previous data from this login attempt.
|
||||
let row = {
|
||||
let query = Query::select()
|
||||
.column(LoginAttempts::UserId)
|
||||
.column(LoginAttempts::ServerLoginData)
|
||||
.from(LoginAttempts::Table)
|
||||
.and_where(Expr::col(LoginAttempts::RandomId).eq(request.login_key.as_str()))
|
||||
.and_where(
|
||||
Expr::col(LoginAttempts::Timestamp)
|
||||
.gt(chrono::Utc::now().naive_utc() - chrono::Duration::minutes(5)),
|
||||
)
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&query).fetch_one(&self.sql_pool).await?
|
||||
};
|
||||
let username = row.get::<String, _>(&*LoginAttempts::UserId.to_string());
|
||||
let login_data = opaque::server::login::ServerLogin::deserialize(
|
||||
&row.get::<Vec<u8>, _>(&*LoginAttempts::ServerLoginData.to_string()),
|
||||
)
|
||||
.map_err(|_| {
|
||||
DomainError::InternalError(format!(
|
||||
"Corrupted login data for user `{}` [id `{}`]",
|
||||
username, request.login_key
|
||||
))
|
||||
})?;
|
||||
let secret_key = self.get_orion_secret_key()?;
|
||||
let login::ServerData {
|
||||
username,
|
||||
server_login,
|
||||
} = bincode::deserialize(&orion::aead::open(
|
||||
&secret_key,
|
||||
&base64::decode(&request.server_data)?,
|
||||
)?)?;
|
||||
// Finish the login: this makes sure the client data is correct, and gives a session key we
|
||||
// don't need.
|
||||
let _session_key =
|
||||
opaque::server::login::finish_login(login_data, request.credential_finalization)?
|
||||
opaque::server::login::finish_login(server_login, request.credential_finalization)?
|
||||
.session_key;
|
||||
|
||||
{
|
||||
// Login was successful, we can delete the login attempt from the table.
|
||||
let delete_query = Query::delete()
|
||||
.from_table(LoginAttempts::Table)
|
||||
.and_where(Expr::col(LoginAttempts::RandomId).eq(request.login_key))
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&delete_query).execute(&self.sql_pool).await?;
|
||||
}
|
||||
Ok(username)
|
||||
}
|
||||
|
||||
@@ -189,36 +161,19 @@ impl OpaqueHandler for SqlOpaqueHandler {
|
||||
&self,
|
||||
request: registration::ClientRegistrationStartRequest,
|
||||
) -> Result<registration::ServerRegistrationStartResponse> {
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
// Generate the server-side key and derive the data to send back.
|
||||
let start_response = opaque::server::registration::start_registration(
|
||||
&mut rng,
|
||||
self.config.get_server_setup(),
|
||||
request.registration_start_request,
|
||||
self.config.get_server_keys().public(),
|
||||
&request.username,
|
||||
)?;
|
||||
// Unique ID to identify the registration attempt.
|
||||
let registration_attempt_id = generate_random_id(&mut rng);
|
||||
{
|
||||
// Write the registration attempt to the DB for the later turn.
|
||||
let query = Query::insert()
|
||||
.into_table(RegistrationAttempts::Table)
|
||||
.columns(vec![
|
||||
RegistrationAttempts::RandomId,
|
||||
RegistrationAttempts::UserId,
|
||||
RegistrationAttempts::ServerRegistrationData,
|
||||
RegistrationAttempts::Timestamp,
|
||||
])
|
||||
.values_panic(vec![
|
||||
registration_attempt_id.as_str().into(),
|
||||
request.username.as_str().into(),
|
||||
start_response.state.serialize().into(),
|
||||
chrono::Utc::now().naive_utc().into(),
|
||||
])
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&query).execute(&self.sql_pool).await?;
|
||||
}
|
||||
let secret_key = self.get_orion_secret_key()?;
|
||||
let server_data = registration::ServerData {
|
||||
username: request.username,
|
||||
};
|
||||
let encrypted_state = orion::aead::seal(&secret_key, &bincode::serialize(&server_data)?)?;
|
||||
Ok(registration::ServerRegistrationStartResponse {
|
||||
registration_key: registration_attempt_id,
|
||||
server_data: base64::encode(encrypted_state),
|
||||
registration_response: start_response.message,
|
||||
})
|
||||
}
|
||||
@@ -227,37 +182,14 @@ impl OpaqueHandler for SqlOpaqueHandler {
|
||||
&self,
|
||||
request: registration::ClientRegistrationFinishRequest,
|
||||
) -> Result<()> {
|
||||
// Fetch the previous state.
|
||||
let row = {
|
||||
let query = Query::select()
|
||||
.column(RegistrationAttempts::UserId)
|
||||
.column(RegistrationAttempts::ServerRegistrationData)
|
||||
.from(RegistrationAttempts::Table)
|
||||
.and_where(
|
||||
Expr::col(RegistrationAttempts::RandomId).eq(request.registration_key.as_str()),
|
||||
)
|
||||
.and_where(
|
||||
Expr::col(RegistrationAttempts::Timestamp)
|
||||
.gt(chrono::Utc::now().naive_utc() - chrono::Duration::minutes(5)),
|
||||
)
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&query).fetch_one(&self.sql_pool).await?
|
||||
};
|
||||
let username = row.get::<String, _>(&*RegistrationAttempts::UserId.to_string());
|
||||
let registration_data = opaque::server::registration::ServerRegistration::deserialize(
|
||||
&row.get::<Vec<u8>, _>(&*RegistrationAttempts::ServerRegistrationData.to_string()),
|
||||
)
|
||||
.map_err(|_| {
|
||||
DomainError::InternalError(format!(
|
||||
"Corrupted registration data for user `{}` [id `{}`]",
|
||||
username, request.registration_key
|
||||
))
|
||||
})?;
|
||||
let secret_key = self.get_orion_secret_key()?;
|
||||
let registration::ServerData { username } = bincode::deserialize(&orion::aead::open(
|
||||
&secret_key,
|
||||
&base64::decode(&request.server_data)?,
|
||||
)?)?;
|
||||
|
||||
let password_file = opaque::server::registration::get_password_file(
|
||||
registration_data,
|
||||
request.registration_upload,
|
||||
)?;
|
||||
let password_file =
|
||||
opaque::server::registration::get_password_file(request.registration_upload);
|
||||
{
|
||||
// Set the user password to the new password.
|
||||
let update_query = Query::update()
|
||||
@@ -270,14 +202,6 @@ impl OpaqueHandler for SqlOpaqueHandler {
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&update_query).execute(&self.sql_pool).await?;
|
||||
}
|
||||
{
|
||||
// Delete the registration attempt.
|
||||
let delete_query = Query::delete()
|
||||
.from_table(RegistrationAttempts::Table)
|
||||
.and_where(Expr::col(RegistrationAttempts::RandomId).eq(request.registration_key))
|
||||
.to_string(DbQueryBuilder {});
|
||||
sqlx::query(&delete_query).execute(&self.sql_pool).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -341,7 +265,7 @@ mod tests {
|
||||
)?;
|
||||
opaque_handler
|
||||
.login_finish(ClientLoginFinishRequest {
|
||||
login_key: start_response.login_key,
|
||||
server_data: start_response.server_data,
|
||||
credential_finalization: login_finish.message,
|
||||
})
|
||||
.await?;
|
||||
@@ -370,7 +294,7 @@ mod tests {
|
||||
)?;
|
||||
opaque_handler
|
||||
.registration_finish(ClientRegistrationFinishRequest {
|
||||
registration_key: start_response.registration_key,
|
||||
server_data: start_response.server_data,
|
||||
registration_upload: registration_finish.message,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -34,27 +34,6 @@ pub enum Memberships {
|
||||
GroupId,
|
||||
}
|
||||
|
||||
/// Contains the temporary data that needs to be kept between the first and second message when
|
||||
/// logging in with the OPAQUE protocol.
|
||||
#[derive(Iden)]
|
||||
pub enum LoginAttempts {
|
||||
Table,
|
||||
RandomId,
|
||||
UserId,
|
||||
ServerLoginData,
|
||||
Timestamp,
|
||||
}
|
||||
|
||||
/// Same for registration.
|
||||
#[derive(Iden)]
|
||||
pub enum RegistrationAttempts {
|
||||
Table,
|
||||
RandomId,
|
||||
UserId,
|
||||
ServerRegistrationData,
|
||||
Timestamp,
|
||||
}
|
||||
|
||||
pub async fn init_table(pool: &Pool) -> sqlx::Result<()> {
|
||||
// SQLite needs this pragma to be turned on. Other DB might not understand this, so ignore the
|
||||
// error.
|
||||
@@ -135,80 +114,6 @@ pub async fn init_table(pool: &Pool) -> sqlx::Result<()> {
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
&Table::create()
|
||||
.table(LoginAttempts::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(LoginAttempts::RandomId)
|
||||
.string_len(32)
|
||||
.primary_key(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(LoginAttempts::UserId)
|
||||
.string_len(255)
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(LoginAttempts::ServerLoginData)
|
||||
.binary()
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(LoginAttempts::Timestamp)
|
||||
.date_time()
|
||||
.not_null(),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKey::create()
|
||||
.name("LoginAttemptsUserIdForeignKey")
|
||||
.table(LoginAttempts::Table, Users::Table)
|
||||
.col(LoginAttempts::UserId, Users::UserId)
|
||||
.on_delete(ForeignKeyAction::Cascade)
|
||||
.on_update(ForeignKeyAction::Cascade),
|
||||
)
|
||||
.to_string(DbQueryBuilder {}),
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
&Table::create()
|
||||
.table(RegistrationAttempts::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(RegistrationAttempts::RandomId)
|
||||
.string_len(32)
|
||||
.primary_key(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(RegistrationAttempts::UserId)
|
||||
.string_len(255)
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(RegistrationAttempts::ServerRegistrationData)
|
||||
.binary()
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(RegistrationAttempts::Timestamp)
|
||||
.date_time()
|
||||
.not_null(),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKey::create()
|
||||
.name("RegistrationAttemptsUserIdForeignKey")
|
||||
.table(RegistrationAttempts::Table, Users::Table)
|
||||
.col(RegistrationAttempts::UserId, Users::UserId)
|
||||
.on_delete(ForeignKeyAction::Cascade)
|
||||
.on_update(ForeignKeyAction::Cascade),
|
||||
)
|
||||
.to_string(DbQueryBuilder {}),
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ use figment::{
|
||||
providers::{Env, Format, Serialized, Toml},
|
||||
Figment,
|
||||
};
|
||||
use lldap_model::{opaque, opaque::KeyPair};
|
||||
use lldap_model::opaque::{server::ServerSetup, KeyPair};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::infra::cli::CLIOpts;
|
||||
@@ -27,18 +27,18 @@ pub struct Configuration {
|
||||
pub key_file: String,
|
||||
#[serde(skip)]
|
||||
#[builder(field(private), setter(strip_option))]
|
||||
server_keys: Option<KeyPair>,
|
||||
server_setup: Option<ServerSetup>,
|
||||
}
|
||||
|
||||
impl ConfigurationBuilder {
|
||||
#[cfg(test)]
|
||||
pub fn build(self) -> Result<Configuration> {
|
||||
let server_keys = get_server_keys(self.key_file.as_deref().unwrap_or("server_key"))?;
|
||||
Ok(self.server_keys(server_keys).private_build()?)
|
||||
let server_setup = get_server_setup(self.key_file.as_deref().unwrap_or("server_key"))?;
|
||||
Ok(self.server_setup(server_setup).private_build()?)
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
if self.server_keys.is_none() {
|
||||
if self.server_setup.is_none() {
|
||||
Err("Don't use `private_build`, use `build` instead".to_string())
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -47,8 +47,12 @@ impl ConfigurationBuilder {
|
||||
}
|
||||
|
||||
impl Configuration {
|
||||
pub fn get_server_setup(&self) -> &ServerSetup {
|
||||
self.server_setup.as_ref().unwrap()
|
||||
}
|
||||
|
||||
pub fn get_server_keys(&self) -> &KeyPair {
|
||||
self.server_keys.as_ref().unwrap()
|
||||
self.get_server_setup().keypair()
|
||||
}
|
||||
|
||||
fn merge_with_cli(mut self: Configuration, cli_opts: CLIOpts) -> Configuration {
|
||||
@@ -80,30 +84,29 @@ impl Configuration {
|
||||
database_url: String::from("sqlite://users.db?mode=rwc"),
|
||||
verbose: false,
|
||||
key_file: String::from("server_key"),
|
||||
server_keys: None,
|
||||
server_setup: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_server_keys(file_path: &str) -> Result<KeyPair> {
|
||||
use opaque_ke::ciphersuite::CipherSuite;
|
||||
fn get_server_setup(file_path: &str) -> Result<ServerSetup> {
|
||||
use std::path::Path;
|
||||
let path = Path::new(file_path);
|
||||
if path.exists() {
|
||||
let bytes = std::fs::read(file_path)
|
||||
.map_err(|e| anyhow!("Could not read key file `{}`: {}", file_path, e))?;
|
||||
Ok(KeyPair::from_private_key_slice(&bytes)?)
|
||||
Ok(ServerSetup::deserialize(&bytes)?)
|
||||
} else {
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
let keypair = opaque::DefaultSuite::generate_random_keypair(&mut rng);
|
||||
std::fs::write(path, keypair.private().as_slice()).map_err(|e| {
|
||||
let server_setup = ServerSetup::new(&mut rng);
|
||||
std::fs::write(path, server_setup.serialize()).map_err(|e| {
|
||||
anyhow!(
|
||||
"Could not write the generated server keys to file `{}`: {}",
|
||||
"Could not write the generated server setup to file `{}`: {}",
|
||||
file_path,
|
||||
e
|
||||
)
|
||||
})?;
|
||||
Ok(keypair)
|
||||
Ok(server_setup)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +119,6 @@ pub fn init(cli_opts: CLIOpts) -> Result<Configuration> {
|
||||
.extract()?;
|
||||
|
||||
let mut config = config.merge_with_cli(cli_opts);
|
||||
config.server_keys = Some(get_server_keys(&config.key_file)?);
|
||||
config.server_setup = Some(get_server_setup(&config.key_file)?);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
domain::sql_tables::{DbQueryBuilder, LoginAttempts, Pool, RegistrationAttempts},
|
||||
domain::sql_tables::{DbQueryBuilder, Pool},
|
||||
infra::jwt_sql_tables::{JwtRefreshStorage, JwtStorage},
|
||||
};
|
||||
use actix::prelude::*;
|
||||
@@ -70,34 +70,6 @@ impl Scheduler {
|
||||
{
|
||||
log::error!("DB error while cleaning up JWT storage: {}", e);
|
||||
};
|
||||
if let Err(e) = sqlx::query(
|
||||
&Query::delete()
|
||||
.from_table(LoginAttempts::Table)
|
||||
.and_where(
|
||||
Expr::col(LoginAttempts::Timestamp)
|
||||
.lt(Local::now().naive_utc() - chrono::Duration::minutes(5)),
|
||||
)
|
||||
.to_string(DbQueryBuilder {}),
|
||||
)
|
||||
.execute(&sql_pool)
|
||||
.await
|
||||
{
|
||||
log::error!("DB error while cleaning up login attempts: {}", e);
|
||||
};
|
||||
if let Err(e) = sqlx::query(
|
||||
&Query::delete()
|
||||
.from_table(RegistrationAttempts::Table)
|
||||
.and_where(
|
||||
Expr::col(RegistrationAttempts::Timestamp)
|
||||
.lt(Local::now().naive_utc() - chrono::Duration::minutes(5)),
|
||||
)
|
||||
.to_string(DbQueryBuilder {}),
|
||||
)
|
||||
.execute(&sql_pool)
|
||||
.await
|
||||
{
|
||||
log::error!("DB error while cleaning up registration attempts: {}", e);
|
||||
};
|
||||
log::info!("DB cleaned!");
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,11 @@ pub(crate) fn error_to_http_response(error: DomainError) -> HttpResponse {
|
||||
DomainError::AuthenticationError(_) | DomainError::AuthenticationProtocolError(_) => {
|
||||
HttpResponse::Unauthorized()
|
||||
}
|
||||
DomainError::DatabaseError(_) | DomainError::InternalError(_) => {
|
||||
HttpResponse::InternalServerError()
|
||||
DomainError::DatabaseError(_)
|
||||
| DomainError::InternalError(_)
|
||||
| DomainError::UnknownCryptoError(_) => HttpResponse::InternalServerError(),
|
||||
DomainError::Base64DecodeError(_) | DomainError::BinarySerializationError(_) => {
|
||||
HttpResponse::BadRequest()
|
||||
}
|
||||
}
|
||||
.body(error.to_string())
|
||||
|
||||
Reference in New Issue
Block a user