aerogramme/src/login/static_provider.rs

190 lines
6.3 KiB
Rust
Raw Normal View History

2022-05-19 10:10:48 +00:00
use std::collections::HashMap;
2023-12-06 19:57:25 +00:00
use std::path::PathBuf;
2023-12-27 13:58:28 +00:00
use std::sync::Arc;
2023-12-14 12:03:04 +00:00
use tokio::signal::unix::{signal, SignalKind};
2023-12-27 13:58:28 +00:00
use tokio::sync::watch;
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-16 10:13:32 +00:00
pub struct ContextualUserEntry {
pub username: String,
pub config: UserEntry,
}
2023-12-14 12:03:04 +00:00
#[derive(Default)]
pub struct UserDatabase {
2023-12-16 10:13:32 +00:00
users: HashMap<String, Arc<ContextualUserEntry>>,
users_by_email: HashMap<String, Arc<ContextualUserEntry>>,
2022-05-19 10:10:48 +00:00
}
2023-12-14 12:03:04 +00:00
pub struct StaticLoginProvider {
user_db: watch::Receiver<UserDatabase>,
in_memory_store: storage::in_memory::MemDb,
2024-02-23 16:01:51 +00:00
garage_store: storage::garage::GarageRoot,
2023-12-14 12:03:04 +00:00
}
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<()> {
2023-12-27 13:58:28 +00:00
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");
2023-12-21 08:32:48 +00:00
stream.recv().await;
2023-12-14 12:03:04 +00:00
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()
2023-12-27 13:58:28 +00:00
.map(|(username, config)| {
(
username.clone(),
Arc::new(ContextualUserEntry { username, config }),
)
})
2022-05-31 13:30:32 +00:00
.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() {
2023-12-16 10:13:32 +00:00
for m in u.config.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);
2023-12-21 08:32:48 +00:00
stream.recv().await;
2023-12-27 13:58:28 +00:00
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());
2023-12-27 13:58:28 +00:00
up.send(UserDatabase {
users,
users_by_email,
})
.context("update user db config")?;
2023-12-14 12:03:04 +00:00
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?;
2023-12-27 13:58:28 +00:00
Ok(Self {
user_db: rx,
in_memory_store: storage::in_memory::MemDb::new(),
2024-02-23 16:31:29 +00:00
garage_store: storage::garage::GarageRoot::new()?,
2023-12-27 13:58:28 +00:00
})
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-20 12:55:23 +00:00
let user = {
let user_db = self.user_db.borrow();
match user_db.users.get(username) {
None => bail!("User {} does not exist", username),
Some(u) => u.clone(),
}
2022-05-31 13:30:32 +00:00
};
2022-05-19 12:33:49 +00:00
2022-06-15 16:40:39 +00:00
tracing::debug!(user=%username, "verify password");
2023-12-16 10:13:32 +00:00
if !verify_password(password, &user.config.password)? {
2022-05-31 13:30:32 +00:00
bail!("Wrong password");
}
2022-06-15 16:40:39 +00:00
tracing::debug!(user=%username, "fetch keys");
2023-12-18 16:09:44 +00:00
let storage: storage::Builder = match &user.config.storage {
StaticStorage::InMemory => self.in_memory_store.builder(username).await,
2023-12-27 13:58:28 +00:00
StaticStorage::Garage(grgconf) => {
2024-02-23 16:01:51 +00:00
self.garage_store.user(storage::garage::GarageConf {
2023-12-27 13:58:28 +00:00
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-16 10:13:32 +00:00
let cr = CryptoRoot(user.config.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-20 12:55:23 +00:00
let user = {
let user_db = self.user_db.borrow();
match user_db.users_by_email.get(email) {
None => bail!("Email {} does not exist", email),
Some(u) => u.clone(),
}
2022-05-31 13:30:32 +00:00
};
2023-12-20 12:55:23 +00:00
tracing::debug!(user=%user.username, "public_login");
2022-05-31 13:30:32 +00:00
2023-12-18 16:09:44 +00:00
let storage: storage::Builder = match &user.config.storage {
StaticStorage::InMemory => self.in_memory_store.builder(&user.username).await,
2023-12-27 13:58:28 +00:00
StaticStorage::Garage(grgconf) => {
2024-02-23 16:01:51 +00:00
self.garage_store.user(storage::garage::GarageConf {
2023-12-27 13:58:28 +00:00
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-16 10:13:32 +00:00
let cr = CryptoRoot(user.config.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
}