fabaccess-bffh/bffhd/users/mod.rs

221 lines
6.4 KiB
Rust
Raw Normal View History

2022-07-24 16:39:33 +02:00
use std::fs;
use lmdb::{Environment, Transaction};
2022-03-15 16:28:11 +01:00
use once_cell::sync::OnceCell;
2022-03-13 17:29:21 +01:00
use rkyv::{Archive, Deserialize, Infallible, Serialize};
2022-03-15 16:28:11 +01:00
use std::collections::HashMap;
2022-07-24 16:39:33 +02:00
use std::fmt::{Display, Formatter};
use std::io::Write;
2022-04-26 23:21:43 +02:00
use clap::ArgMatches;
use miette::{Context, Diagnostic, IntoDiagnostic, SourceOffset, SourceSpan};
2022-03-13 22:50:37 +01:00
use std::path::Path;
2022-03-10 20:52:34 +01:00
use std::sync::Arc;
use thiserror::Error;
2021-11-26 22:11:24 +01:00
2022-03-13 17:29:21 +01:00
pub mod db;
2021-12-06 21:53:42 +01:00
2022-03-13 22:50:37 +01:00
use crate::users::db::UserData;
2022-03-15 16:28:11 +01:00
use crate::UserDB;
2021-11-26 22:11:24 +01:00
2022-03-13 17:29:21 +01:00
#[derive(
Clone,
PartialEq,
Eq,
Debug,
Archive,
Serialize,
Deserialize,
serde::Serialize,
serde::Deserialize,
)]
2022-03-13 22:50:37 +01:00
#[archive_attr(derive(Debug, PartialEq))]
2022-03-15 17:52:47 +01:00
pub struct UserRef {
2022-03-16 18:10:59 +01:00
pub id: String,
}
impl PartialEq<ArchivedUserRef> for UserRef {
fn eq(&self, other: &ArchivedUserRef) -> bool {
self.id == other.id
}
}
impl PartialEq<UserRef> for ArchivedUserRef {
fn eq(&self, other: &UserRef) -> bool {
self.id == other.id
}
2021-11-26 22:11:24 +01:00
}
2022-03-20 22:46:04 +01:00
impl Display for ArchivedUserRef {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.id.as_str())
}
}
2022-03-15 17:52:47 +01:00
impl UserRef {
2022-03-13 22:50:37 +01:00
pub fn new(id: String) -> Self {
2022-03-15 17:52:47 +01:00
UserRef { id }
2021-12-17 16:43:31 +01:00
}
2022-03-13 17:29:21 +01:00
pub fn get_username(&self) -> &str {
2022-03-13 22:50:37 +01:00
self.id.as_str()
2022-03-13 17:29:21 +01:00
}
}
2022-03-13 22:50:37 +01:00
2022-03-15 16:28:11 +01:00
static USERDB: OnceCell<UserDB> = OnceCell::new();
2022-03-13 22:50:37 +01:00
2022-03-16 19:29:36 +01:00
#[derive(Copy, Clone, Debug)]
2022-03-15 16:28:11 +01:00
#[repr(transparent)]
2022-03-13 22:50:37 +01:00
pub struct Users {
2022-03-15 16:28:11 +01:00
userdb: &'static UserDB,
2022-03-13 22:50:37 +01:00
}
#[derive(Clone, Debug, PartialEq, Eq, Error, Diagnostic)]
#[error(transparent)]
#[repr(transparent)]
pub struct Error(#[from] pub db::Error);
2022-03-13 22:50:37 +01:00
impl Users {
pub fn new(env: Arc<Environment>) -> Result<Self, Error> {
2022-03-15 16:28:11 +01:00
let span = tracing::debug_span!("users", ?env, "Creating Users handle");
let _guard = span.enter();
let userdb = USERDB.get_or_try_init(|| {
tracing::debug!("Global resource not yet initialized, initializing…");
unsafe { UserDB::create(env) }
})?;
2022-03-15 16:28:11 +01:00
Ok(Self { userdb })
}
2022-03-15 19:56:41 +01:00
pub(crate) fn into_inner(self) -> &'static UserDB {
self.userdb
}
2022-03-15 16:28:11 +01:00
pub fn get_user(&self, uid: &str) -> Option<db::User> {
tracing::trace!(uid, "Looking up user");
2022-05-05 15:50:44 +02:00
self.userdb.get(uid).unwrap().map(|user| {
Deserialize::<db::User, _>::deserialize(user.as_ref(), &mut Infallible).unwrap()
})
}
pub fn get_user_by_token(&self, token: &str) -> Option<db::User> {
tracing::trace!(token, "Looking up user by token");
self.userdb.get_by_token(token).unwrap().map(|user| {
2022-05-05 15:50:44 +02:00
Deserialize::<db::User, _>::deserialize(user.as_ref(), &mut Infallible).unwrap()
})
2022-03-13 22:50:37 +01:00
}
2022-06-02 17:46:26 +02:00
pub fn put_user(&self, uid: &str, user: &db::User) -> Result<(), crate::db::Error> {
2022-03-21 00:01:50 +01:00
tracing::trace!(uid, ?user, "Updating user");
self.userdb.put(uid, user)
}
2022-06-02 17:46:26 +02:00
pub fn del_user(&self, uid: &str) -> Result<(), crate::db::Error> {
tracing::trace!(uid, "Deleting user");
self.userdb.delete(uid)
}
pub fn load_file(&self, path_str: &str) -> miette::Result<()> {
let path: &Path = Path::new(path_str);
if path.is_dir() {
#[derive(Debug, Error, Diagnostic)]
#[error("load takes a file, not a directory")]
#[diagnostic(
code(load::file),
url("https://gitlab.com/fabinfra/fabaccess/bffh/-/issues/55")
)]
struct LoadIsDirError {
#[source_code]
src: String,
#[label("path provided")]
dir_path: SourceSpan,
#[help]
help: String,
}
Err(LoadIsDirError {
src: format!("--load {}", path_str),
dir_path: (7, path_str.as_bytes().len()).into(),
help: format!(
"Provide a path to a file instead, e.g. {}/users.toml",
path_str
),
})?;
return Ok(());
}
2022-06-02 17:46:26 +02:00
let f = std::fs::read(path).into_diagnostic()?;
let map: HashMap<String, UserData> = toml::from_slice(&f).into_diagnostic()?;
2022-03-13 22:50:37 +01:00
let mut txn = unsafe { self.userdb.get_rw_txn()? };
self.userdb.clear_txn(&mut txn)?;
2022-03-13 22:50:37 +01:00
for (uid, mut userdata) in map {
2022-03-15 16:28:11 +01:00
userdata.passwd = userdata.passwd.map(|pw| {
if !pw.starts_with("$argon2") {
let config = argon2::Config::default();
let salt: [u8; 16] = rand::random();
let hash = argon2::hash_encoded(pw.as_bytes(), &salt, &config)
.expect(&format!("Failed to hash password for {}: ", uid));
tracing::debug!("Hashed pw for {} to {}", uid, hash);
hash
} else {
pw
}
2022-03-13 22:50:37 +01:00
});
2022-03-15 16:28:11 +01:00
let user = db::User {
id: uid.clone(),
userdata,
};
2022-03-13 22:50:37 +01:00
tracing::trace!(%uid, ?user, "Storing user object");
if let Err(e) = self.userdb.put_txn(&mut txn, uid.as_str(), &user) {
tracing::warn!(error=?e, "failed to add user")
}
2022-03-13 22:50:37 +01:00
}
2022-06-02 17:46:26 +02:00
txn.commit().map_err(crate::db::Error::from)?;
2022-03-13 22:50:37 +01:00
Ok(())
}
2022-07-24 16:39:33 +02:00
pub fn dump_file(&self, path_str: &str, force: bool) -> miette::Result<usize> {
let path = Path::new(path_str);
let exists = path.exists();
if exists {
if !force {
#[derive(Debug, Error, Diagnostic)]
#[error("given file already exists, refusing to clobber")]
#[diagnostic(code(dump::clobber))]
struct DumpFileExists {
#[source_code]
src: String,
#[label("file provided")]
dir_path: SourceSpan,
#[help]
help: &'static str,
}
Err(DumpFileExists {
src: format!("--load {}", path_str),
dir_path: (7, path_str.as_bytes().len()).into(),
help: "to force overwriting the file add `--force` as argument",
})?;
} else {
tracing::info!("output file already exists, overwriting due to `--force`");
}
}
let mut file = fs::File::create(path).into_diagnostic()?;
let users = self.userdb.get_all()?;
let encoded = toml::ser::to_vec(&users).into_diagnostic()?;
file.write_all(&encoded[..]).into_diagnostic()?;
Ok(0)
}
2022-03-15 16:28:11 +01:00
}