aerogramme/src/login/static_provider.rs

158 lines
5.3 KiB
Rust
Raw Normal View History

2022-05-19 10:10:48 +00:00
use std::collections::HashMap;
2022-05-31 13:30:32 +00:00
use std::sync::Arc;
2023-12-06 19:57:25 +00:00
use std::path::PathBuf;
2023-12-14 12:03:04 +00:00
use tokio::sync::watch;
use tokio::signal::unix::{signal, SignalKind};
2022-05-19 10:10:48 +00:00
use anyhow::{anyhow, bail, Result};
use async_trait::async_trait;
use crate::config::*;
use crate::login::*;
2023-11-17 15:42:25 +00:00
use crate::storage;
2022-05-19 10:10:48 +00:00
2023-12-14 12:03:04 +00:00
#[derive(Default)]
pub struct UserDatabase {
2023-12-06 19:57:25 +00:00
users: HashMap<String, Arc<UserEntry>>,
users_by_email: HashMap<String, Arc<UserEntry>>,
2022-05-19 10:10:48 +00:00
}
2023-12-14 12:03:04 +00:00
pub struct StaticLoginProvider {
user_db: watch::Receiver<UserDatabase>,
}
2023-12-06 19:57:25 +00:00
2023-12-14 12:03:04 +00:00
pub async fn update_user_list(config: PathBuf, up: watch::Sender<UserDatabase>) -> Result<()> {
let mut stream = signal(SignalKind::user_defined1()).expect("failed to install SIGUSR1 signal hander for reload");
2023-12-06 19:57:25 +00:00
2023-12-14 12:03:04 +00:00
loop {
let ulist: UserList = match read_config(config.clone()) {
Ok(x) => x,
Err(e) => {
tracing::warn!(path=%config.as_path().to_string_lossy(), error=%e, "Unable to load config");
continue;
}
};
2023-12-06 19:57:25 +00:00
2023-12-14 12:03:04 +00:00
let users = ulist
2022-05-31 13:30:32 +00:00
.into_iter()
.map(|(k, v)| (k, Arc::new(v)))
.collect::<HashMap<_, _>>();
2023-12-08 17:13:00 +00:00
2023-12-14 12:03:04 +00:00
let mut users_by_email = HashMap::new();
for (_, u) in users.iter() {
2022-05-31 13:30:32 +00:00
for m in u.email_addresses.iter() {
2023-12-14 12:03:04 +00:00
if users_by_email.contains_key(m) {
tracing::warn!("Several users have the same email address: {}", m);
continue
2022-05-31 13:30:32 +00:00
}
2023-12-14 12:03:04 +00:00
users_by_email.insert(m.clone(), u.clone());
2022-05-31 13:30:32 +00:00
}
}
2023-12-14 12:03:04 +00:00
tracing::info!("{} users loaded", users.len());
up.send(UserDatabase { users, users_by_email }).context("update user db config")?;
stream.recv().await;
tracing::info!("Received SIGUSR1, reloading");
}
}
impl StaticLoginProvider {
pub async fn new(config: LoginStaticConfig) -> Result<Self> {
let (tx, mut rx) = watch::channel(UserDatabase::default());
tokio::spawn(update_user_list(config.user_list, tx));
rx.changed().await?;
Ok(Self { user_db: rx })
2022-05-19 10:10:48 +00:00
}
}
#[async_trait]
impl LoginProvider for StaticLoginProvider {
async fn login(&self, username: &str, password: &str) -> Result<Credentials> {
2022-06-03 12:00:19 +00:00
tracing::debug!(user=%username, "login");
2023-12-14 12:03:04 +00:00
let user_db = self.user_db.borrow();
let user = match user_db.users.get(username) {
2022-05-19 10:10:48 +00:00
None => bail!("User {} does not exist", username),
2022-05-31 13:30:32 +00:00
Some(u) => u,
};
2022-05-19 12:33:49 +00:00
2022-06-15 16:40:39 +00:00
tracing::debug!(user=%username, "verify password");
2022-05-31 13:30:32 +00:00
if !verify_password(password, &user.password)? {
bail!("Wrong password");
}
2022-06-15 16:40:39 +00:00
tracing::debug!(user=%username, "fetch keys");
2023-11-23 16:19:35 +00:00
let storage: storage::Builders = match &user.storage {
2023-11-17 17:46:22 +00:00
StaticStorage::InMemory => Box::new(storage::in_memory::FullMem {}),
2023-11-23 16:19:35 +00:00
StaticStorage::Garage(grgconf) => Box::new(storage::garage::GrgCreds {
region: grgconf.aws_region.clone(),
k2v_endpoint: grgconf.k2v_endpoint.clone(),
s3_endpoint: grgconf.s3_endpoint.clone(),
aws_access_key_id: grgconf.aws_access_key_id.clone(),
aws_secret_access_key: grgconf.aws_secret_access_key.clone(),
bucket: grgconf.bucket.clone(),
}),
2023-11-17 17:46:22 +00:00
};
2023-12-13 17:04:04 +00:00
let cr = CryptoRoot(user.crypto_root.clone());
2023-12-13 15:09:01 +00:00
let keys = cr.crypto_keys(password)?;
2022-05-31 13:30:32 +00:00
2022-06-15 16:40:39 +00:00
tracing::debug!(user=%username, "logged");
2022-05-31 13:30:32 +00:00
Ok(Credentials { storage, keys })
}
async fn public_login(&self, email: &str) -> Result<PublicCredentials> {
2023-12-14 12:03:04 +00:00
let user_db = self.user_db.borrow();
let user = match user_db.users_by_email.get(email) {
2022-05-31 13:30:32 +00:00
None => bail!("No user for email address {}", email),
Some(u) => u,
};
2023-11-23 16:19:35 +00:00
let storage: storage::Builders = match &user.storage {
2023-11-23 14:16:44 +00:00
StaticStorage::InMemory => Box::new(storage::in_memory::FullMem {}),
2023-11-23 16:19:35 +00:00
StaticStorage::Garage(grgconf) => Box::new(storage::garage::GrgCreds {
region: grgconf.aws_region.clone(),
k2v_endpoint: grgconf.k2v_endpoint.clone(),
s3_endpoint: grgconf.s3_endpoint.clone(),
aws_access_key_id: grgconf.aws_access_key_id.clone(),
aws_secret_access_key: grgconf.aws_secret_access_key.clone(),
bucket: grgconf.bucket.clone(),
}),
2022-05-31 13:30:32 +00:00
};
2023-12-13 17:04:04 +00:00
let cr = CryptoRoot(user.crypto_root.clone());
2023-12-13 15:09:01 +00:00
let public_key = cr.public_key()?;
2022-05-31 13:30:32 +00:00
Ok(PublicCredentials {
storage,
public_key,
})
2022-05-19 10:10:48 +00:00
}
}
2022-05-19 13:14:36 +00:00
pub fn hash_password(password: &str) -> Result<String> {
use argon2::{
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
Argon2,
};
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
Ok(argon2
.hash_password(password.as_bytes(), &salt)
.map_err(|e| anyhow!("Argon2 error: {}", e))?
.to_string())
2022-05-19 13:14:36 +00:00
}
pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
use argon2::{
2022-05-20 10:49:53 +00:00
password_hash::{PasswordHash, PasswordVerifier},
Argon2,
};
let parsed_hash =
2023-05-15 16:23:23 +00:00
PasswordHash::new(hash).map_err(|e| anyhow!("Invalid hashed password: {}", e))?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok())
2022-05-19 13:14:36 +00:00
}