Refactor dependencies to reduce code base size #111

Merged
pierre merged 4 commits from dep-refactoring into master 2023-04-29 11:11:25 +00:00
5 changed files with 20 additions and 102 deletions
Showing only changes of commit 2eaeb12835 - Show all commits

19
Cargo.lock generated
View File

@ -561,7 +561,6 @@ dependencies = [
"actix-remote-ip", "actix-remote-ip",
"actix-session", "actix-session",
"actix-web", "actix-web",
"aes-gcm",
"askama", "askama",
"base32", "base32",
"base64 0.21.0", "base64 0.21.0",
@ -576,6 +575,7 @@ dependencies = [
"jwt-simple", "jwt-simple",
"lazy-regex", "lazy-regex",
"lazy_static", "lazy_static",
"light-openid",
"log", "log",
"mime_guess", "mime_guess",
"qrcode-generator", "qrcode-generator",
@ -1765,6 +1765,23 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb"
[[package]]
name = "light-openid"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "608aa1b7148a6eeab631c6267deca33407ff851ab50eea115e52c13a9bb184ee"
dependencies = [
"aes-gcm",
"base64 0.21.0",
"bincode",
"log",
"rand",
"reqwest",
"serde",
"serde_json",
"urlencoding",
]
[[package]] [[package]]
name = "link-cplusplus" name = "link-cplusplus"
version = "1.0.8" version = "1.0.8"

View File

@ -35,7 +35,7 @@ base32 = "0.4.0"
qrcode-generator = "4.1.8" qrcode-generator = "4.1.8"
webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation"] } webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation"] }
url = "2.3.1" url = "2.3.1"
aes-gcm = { version = "0.10.1", features = ["aes"] } light-openid = { version = "1.0.1", features=["crypto-wrapper"] }
bincode = "2.0.0-rc.3" bincode = "2.0.0-rc.3"
chrono = "0.4.24" chrono = "0.4.24"
lazy_static = "1.4.0" lazy_static = "1.4.0"

View File

@ -1,98 +0,0 @@
use std::io::ErrorKind;
use aes_gcm::aead::{Aead, OsRng};
use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use bincode::{Decode, Encode};
use rand::Rng;
use crate::utils::err::Res;
const NONCE_LEN: usize = 12;
pub struct CryptoWrapper {
key: Key<Aes256Gcm>,
}
impl CryptoWrapper {
/// Generate a new memory wrapper
pub fn new_random() -> Self {
Self {
key: Aes256Gcm::generate_key(&mut OsRng),
}
}
/// Encrypt some data
pub fn encrypt<T: Encode + Decode>(&self, data: &T) -> Res<String> {
let aes_key = Aes256Gcm::new(&self.key);
let nonce_bytes = rand::thread_rng().gen::<[u8; NONCE_LEN]>();
let serialized_data = bincode::encode_to_vec(data, bincode::config::standard())?;
let mut enc = aes_key
.encrypt(Nonce::from_slice(&nonce_bytes), serialized_data.as_slice())
.unwrap();
enc.extend_from_slice(&nonce_bytes);
Ok(BASE64_STANDARD.encode(enc))
}
/// Decrypt some data previously encrypted using the [`CryptoWrapper::encrypt`] method
pub fn decrypt<T: Decode>(&self, input: &str) -> Res<T> {
let bytes = BASE64_STANDARD.decode(input)?;
if bytes.len() < NONCE_LEN {
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Input string is smaller than nonce!",
)));
}
let (enc, nonce) = bytes.split_at(bytes.len() - NONCE_LEN);
assert_eq!(nonce.len(), NONCE_LEN);
let aes_key = Aes256Gcm::new(&self.key);
let dec = match aes_key.decrypt(Nonce::from_slice(nonce), enc) {
Ok(d) => d,
Err(e) => {
log::error!("Failed to decrypt wrapped data! {:#?}", e);
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Failed to decrypt wrapped data!",
)));
}
};
Ok(bincode::decode_from_slice(&dec, bincode::config::standard())?.0)
}
}
#[cfg(test)]
mod test {
use crate::data::crypto_wrapper::CryptoWrapper;
use bincode::{Decode, Encode};
#[derive(Encode, Decode, Eq, PartialEq, Debug)]
struct Message(String);
#[test]
fn encrypt_and_decrypt() {
let wrapper = CryptoWrapper::new_random();
let msg = Message("Pierre was here".to_string());
let enc = wrapper.encrypt(&msg).unwrap();
let dec: Message = wrapper.decrypt(&enc).unwrap();
assert_eq!(dec, msg)
}
#[test]
fn encrypt_and_decrypt_invalid() {
let wrapper_1 = CryptoWrapper::new_random();
let wrapper_2 = CryptoWrapper::new_random();
let msg = Message("Pierre was here".to_string());
let enc = wrapper_1.encrypt(&msg).unwrap();
wrapper_2.decrypt::<Message>(&enc).unwrap_err();
}
}

View File

@ -3,7 +3,6 @@ pub mod action_logger;
pub mod app_config; pub mod app_config;
pub mod client; pub mod client;
pub mod code_challenge; pub mod code_challenge;
pub mod crypto_wrapper;
pub mod current_user; pub mod current_user;
pub mod entity_manager; pub mod entity_manager;
pub mod id_token; pub mod id_token;

View File

@ -3,6 +3,7 @@ use std::sync::Arc;
use actix_web::web; use actix_web::web;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use light_openid::crypto_wrapper::CryptoWrapper;
use uuid::Uuid; use uuid::Uuid;
use webauthn_rs::prelude::{ use webauthn_rs::prelude::{
CreationChallengeResponse, Passkey, PublicKeyCredential, RegisterPublicKeyCredential, CreationChallengeResponse, Passkey, PublicKeyCredential, RegisterPublicKeyCredential,
@ -14,7 +15,6 @@ use crate::constants::{
APP_NAME, WEBAUTHN_LOGIN_CHALLENGE_EXPIRE, WEBAUTHN_REGISTER_CHALLENGE_EXPIRE, APP_NAME, WEBAUTHN_LOGIN_CHALLENGE_EXPIRE, WEBAUTHN_REGISTER_CHALLENGE_EXPIRE,
}; };
use crate::data::app_config::AppConfig; use crate::data::app_config::AppConfig;
use crate::data::crypto_wrapper::CryptoWrapper;
use crate::data::user::{User, UserID}; use crate::data::user::{User, UserID};
use crate::utils::err::Res; use crate::utils::err::Res;
use crate::utils::time::time; use crate::utils::time::time;