2021-11-09 01:31:27 +08:00
|
|
|
use std::borrow::Cow;
|
2021-12-06 22:45:41 +08:00
|
|
|
use std::cmp::Reverse;
|
2021-11-09 01:31:27 +08:00
|
|
|
use std::convert::TryFrom;
|
|
|
|
use std::convert::TryInto;
|
|
|
|
use std::fs::create_dir_all;
|
|
|
|
use std::path::Path;
|
|
|
|
use std::str;
|
2021-12-16 00:55:39 +08:00
|
|
|
use std::sync::Arc;
|
2021-11-09 01:31:27 +08:00
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
use enum_iterator::IntoEnumIterator;
|
2022-03-16 20:45:58 +08:00
|
|
|
use milli::heed::types::{ByteSlice, DecodeIgnore, SerdeJson};
|
|
|
|
use milli::heed::{Database, Env, EnvOpenOptions, RwTxn};
|
2022-05-25 16:32:47 +08:00
|
|
|
use sha2::{Digest, Sha256};
|
2022-02-14 22:32:41 +08:00
|
|
|
use time::OffsetDateTime;
|
2022-05-25 16:32:47 +08:00
|
|
|
use uuid::Uuid;
|
2021-11-09 01:31:27 +08:00
|
|
|
|
|
|
|
use super::error::Result;
|
|
|
|
use super::{Action, Key};
|
|
|
|
|
|
|
|
const AUTH_STORE_SIZE: usize = 1_073_741_824; //1GiB
|
|
|
|
const AUTH_DB_PATH: &str = "auth";
|
|
|
|
const KEY_DB_NAME: &str = "api-keys";
|
|
|
|
const KEY_ID_ACTION_INDEX_EXPIRATION_DB_NAME: &str = "keyid-action-index-expiration";
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
pub type KeyId = Uuid;
|
2021-11-09 01:31:27 +08:00
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct HeedAuthStore {
|
2021-12-16 00:55:39 +08:00
|
|
|
env: Arc<Env>,
|
2021-11-09 01:31:27 +08:00
|
|
|
keys: Database<ByteSlice, SerdeJson<Key>>,
|
2022-02-14 22:32:41 +08:00
|
|
|
action_keyid_index_expiration: Database<KeyIdActionCodec, SerdeJson<Option<OffsetDateTime>>>,
|
2022-02-09 20:55:36 +08:00
|
|
|
should_close_on_drop: bool,
|
2021-11-09 01:31:27 +08:00
|
|
|
}
|
|
|
|
|
2021-12-16 00:55:39 +08:00
|
|
|
impl Drop for HeedAuthStore {
|
|
|
|
fn drop(&mut self) {
|
2022-02-09 20:55:36 +08:00
|
|
|
if self.should_close_on_drop && Arc::strong_count(&self.env) == 1 {
|
2021-12-16 00:55:39 +08:00
|
|
|
self.env.as_ref().clone().prepare_for_closing();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-16 20:45:58 +08:00
|
|
|
pub fn open_auth_store_env(path: &Path) -> milli::heed::Result<milli::heed::Env> {
|
2022-02-23 01:16:02 +08:00
|
|
|
let mut options = EnvOpenOptions::new();
|
|
|
|
options.map_size(AUTH_STORE_SIZE); // 1GB
|
|
|
|
options.max_dbs(2);
|
|
|
|
options.open(path)
|
|
|
|
}
|
|
|
|
|
2021-11-09 01:31:27 +08:00
|
|
|
impl HeedAuthStore {
|
|
|
|
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
|
|
|
|
let path = path.as_ref().join(AUTH_DB_PATH);
|
|
|
|
create_dir_all(&path)?;
|
2022-02-23 01:16:02 +08:00
|
|
|
let env = Arc::new(open_auth_store_env(path.as_ref())?);
|
2021-11-09 01:31:27 +08:00
|
|
|
let keys = env.create_database(Some(KEY_DB_NAME))?;
|
|
|
|
let action_keyid_index_expiration =
|
|
|
|
env.create_database(Some(KEY_ID_ACTION_INDEX_EXPIRATION_DB_NAME))?;
|
|
|
|
Ok(Self {
|
|
|
|
env,
|
|
|
|
keys,
|
|
|
|
action_keyid_index_expiration,
|
2022-02-09 20:55:36 +08:00
|
|
|
should_close_on_drop: true,
|
2021-11-09 01:31:27 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-02-09 20:55:36 +08:00
|
|
|
pub fn set_drop_on_close(&mut self, v: bool) {
|
|
|
|
self.should_close_on_drop = v;
|
|
|
|
}
|
|
|
|
|
2021-11-09 01:31:27 +08:00
|
|
|
pub fn is_empty(&self) -> Result<bool> {
|
|
|
|
let rtxn = self.env.read_txn()?;
|
|
|
|
|
|
|
|
Ok(self.keys.len(&rtxn)? == 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn put_api_key(&self, key: Key) -> Result<Key> {
|
2022-05-25 16:32:47 +08:00
|
|
|
let uid = key.uid;
|
2021-11-09 01:31:27 +08:00
|
|
|
let mut wtxn = self.env.write_txn()?;
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
self.keys.put(&mut wtxn, uid.as_bytes(), &key)?;
|
|
|
|
|
2021-11-09 01:31:27 +08:00
|
|
|
// delete key from inverted database before refilling it.
|
2022-05-25 16:32:47 +08:00
|
|
|
self.delete_key_from_inverted_db(&mut wtxn, &uid)?;
|
2021-11-09 01:31:27 +08:00
|
|
|
// create inverted database.
|
|
|
|
let db = self.action_keyid_index_expiration;
|
|
|
|
|
|
|
|
let actions = if key.actions.contains(&Action::All) {
|
|
|
|
// if key.actions contains All, we iterate over all actions.
|
|
|
|
Action::into_enum_iter().collect()
|
|
|
|
} else {
|
|
|
|
key.actions.clone()
|
|
|
|
};
|
|
|
|
|
|
|
|
let no_index_restriction = key.indexes.contains(&"*".to_owned());
|
|
|
|
for action in actions {
|
|
|
|
if no_index_restriction {
|
|
|
|
// If there is no index restriction we put None.
|
2022-05-25 16:32:47 +08:00
|
|
|
db.put(&mut wtxn, &(&uid, &action, None), &key.expires_at)?;
|
2021-11-09 01:31:27 +08:00
|
|
|
} else {
|
|
|
|
// else we create a key for each index.
|
|
|
|
for index in key.indexes.iter() {
|
|
|
|
db.put(
|
|
|
|
&mut wtxn,
|
2022-05-25 16:32:47 +08:00
|
|
|
&(&uid, &action, Some(index.as_bytes())),
|
2021-11-09 01:31:27 +08:00
|
|
|
&key.expires_at,
|
|
|
|
)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
wtxn.commit()?;
|
|
|
|
|
|
|
|
Ok(key)
|
|
|
|
}
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
pub fn get_api_key(&self, uid: Uuid) -> Result<Option<Key>> {
|
2021-11-09 01:31:27 +08:00
|
|
|
let rtxn = self.env.read_txn()?;
|
2022-05-25 16:32:47 +08:00
|
|
|
self.keys.get(&rtxn, uid.as_bytes()).map_err(|e| e.into())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_uid_from_sha(&self, key_sha: &[u8], master_key: &[u8]) -> Result<Option<Uuid>> {
|
|
|
|
let rtxn = self.env.read_txn()?;
|
|
|
|
let uid = self
|
|
|
|
.keys
|
|
|
|
.remap_data_type::<DecodeIgnore>()
|
|
|
|
.iter(&rtxn)?
|
|
|
|
.filter_map(|res| match res {
|
|
|
|
Ok((uid, _)) if generate_key(uid, master_key).as_bytes() == key_sha => {
|
|
|
|
let (uid, _) = try_split_array_at(uid)?;
|
|
|
|
Some(Uuid::from_bytes(*uid))
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
.next();
|
|
|
|
|
|
|
|
Ok(uid)
|
2021-11-09 01:31:27 +08:00
|
|
|
}
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
pub fn delete_api_key(&self, uid: Uuid) -> Result<bool> {
|
2021-11-09 01:31:27 +08:00
|
|
|
let mut wtxn = self.env.write_txn()?;
|
2022-05-25 16:32:47 +08:00
|
|
|
let existing = self.keys.delete(&mut wtxn, uid.as_bytes())?;
|
|
|
|
self.delete_key_from_inverted_db(&mut wtxn, &uid)?;
|
2021-11-09 01:31:27 +08:00
|
|
|
wtxn.commit()?;
|
|
|
|
|
|
|
|
Ok(existing)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn list_api_keys(&self) -> Result<Vec<Key>> {
|
|
|
|
let mut list = Vec::new();
|
|
|
|
let rtxn = self.env.read_txn()?;
|
|
|
|
for result in self.keys.remap_key_type::<DecodeIgnore>().iter(&rtxn)? {
|
|
|
|
let (_, content) = result?;
|
|
|
|
list.push(content);
|
|
|
|
}
|
2021-12-06 22:45:41 +08:00
|
|
|
list.sort_unstable_by_key(|k| Reverse(k.created_at));
|
2021-11-09 01:31:27 +08:00
|
|
|
Ok(list)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_expiration_date(
|
|
|
|
&self,
|
2022-05-25 16:32:47 +08:00
|
|
|
uid: Uuid,
|
2021-11-09 01:31:27 +08:00
|
|
|
action: Action,
|
|
|
|
index: Option<&[u8]>,
|
2022-02-14 22:32:41 +08:00
|
|
|
) -> Result<Option<Option<OffsetDateTime>>> {
|
2021-11-09 01:31:27 +08:00
|
|
|
let rtxn = self.env.read_txn()?;
|
2022-05-25 16:32:47 +08:00
|
|
|
let tuple = (&uid, &action, index);
|
|
|
|
Ok(self.action_keyid_index_expiration.get(&rtxn, &tuple)?)
|
2021-11-09 01:31:27 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn prefix_first_expiration_date(
|
|
|
|
&self,
|
2022-05-25 16:32:47 +08:00
|
|
|
uid: Uuid,
|
2021-11-09 01:31:27 +08:00
|
|
|
action: Action,
|
2022-02-14 22:32:41 +08:00
|
|
|
) -> Result<Option<Option<OffsetDateTime>>> {
|
2021-11-09 01:31:27 +08:00
|
|
|
let rtxn = self.env.read_txn()?;
|
2022-05-25 16:32:47 +08:00
|
|
|
let tuple = (&uid, &action, None);
|
|
|
|
let exp = self
|
|
|
|
.action_keyid_index_expiration
|
|
|
|
.prefix_iter(&rtxn, &tuple)?
|
|
|
|
.next()
|
|
|
|
.transpose()?
|
|
|
|
.map(|(_, expiration)| expiration);
|
2021-11-09 01:31:27 +08:00
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
Ok(exp)
|
2022-01-12 22:35:33 +08:00
|
|
|
}
|
|
|
|
|
2021-11-09 01:31:27 +08:00
|
|
|
fn delete_key_from_inverted_db(&self, wtxn: &mut RwTxn, key: &KeyId) -> Result<()> {
|
|
|
|
let mut iter = self
|
|
|
|
.action_keyid_index_expiration
|
|
|
|
.remap_types::<ByteSlice, DecodeIgnore>()
|
2022-05-25 16:32:47 +08:00
|
|
|
.prefix_iter_mut(wtxn, key.as_bytes())?;
|
2021-11-09 01:31:27 +08:00
|
|
|
while iter.next().transpose()?.is_some() {
|
|
|
|
// safety: we don't keep references from inside the LMDB database.
|
|
|
|
unsafe { iter.del_current()? };
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Codec allowing to retrieve the expiration date of an action,
|
|
|
|
/// optionnally on a spcific index, for a given key.
|
|
|
|
pub struct KeyIdActionCodec;
|
|
|
|
|
2022-03-16 20:45:58 +08:00
|
|
|
impl<'a> milli::heed::BytesDecode<'a> for KeyIdActionCodec {
|
2021-11-09 01:31:27 +08:00
|
|
|
type DItem = (KeyId, Action, Option<&'a [u8]>);
|
|
|
|
|
|
|
|
fn bytes_decode(bytes: &'a [u8]) -> Option<Self::DItem> {
|
2022-05-25 16:32:47 +08:00
|
|
|
let (key_id_bytes, action_bytes) = try_split_array_at(bytes)?;
|
2021-11-09 01:31:27 +08:00
|
|
|
let (action_bytes, index) = match try_split_array_at(action_bytes)? {
|
|
|
|
(action, []) => (action, None),
|
|
|
|
(action, index) => (action, Some(index)),
|
|
|
|
};
|
2022-05-25 16:32:47 +08:00
|
|
|
let key_id = Uuid::from_bytes(*key_id_bytes);
|
2021-11-09 01:31:27 +08:00
|
|
|
let action = Action::from_repr(u8::from_be_bytes(*action_bytes))?;
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
Some((key_id, action, index))
|
2021-11-09 01:31:27 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-16 20:45:58 +08:00
|
|
|
impl<'a> milli::heed::BytesEncode<'a> for KeyIdActionCodec {
|
2021-11-09 01:31:27 +08:00
|
|
|
type EItem = (&'a KeyId, &'a Action, Option<&'a [u8]>);
|
|
|
|
|
|
|
|
fn bytes_encode((key_id, action, index): &Self::EItem) -> Option<Cow<[u8]>> {
|
|
|
|
let mut bytes = Vec::new();
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
bytes.extend_from_slice(key_id.as_bytes());
|
2021-11-09 01:31:27 +08:00
|
|
|
let action_bytes = u8::to_be_bytes(action.repr());
|
|
|
|
bytes.extend_from_slice(&action_bytes);
|
|
|
|
if let Some(index) = index {
|
|
|
|
bytes.extend_from_slice(index);
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(Cow::Owned(bytes))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-25 16:32:47 +08:00
|
|
|
pub fn generate_key(uid: &[u8], master_key: &[u8]) -> String {
|
|
|
|
let key = [uid, master_key].concat();
|
|
|
|
let sha = Sha256::digest(&key);
|
2022-06-01 21:50:13 +08:00
|
|
|
base64::encode_config(sha, base64::URL_SAFE_NO_PAD)
|
2022-05-25 16:32:47 +08:00
|
|
|
}
|
|
|
|
|
2021-11-09 01:31:27 +08:00
|
|
|
/// Divides one slice into two at an index, returns `None` if mid is out of bounds.
|
|
|
|
pub fn try_split_at<T>(slice: &[T], mid: usize) -> Option<(&[T], &[T])> {
|
|
|
|
if mid <= slice.len() {
|
|
|
|
Some(slice.split_at(mid))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Divides one slice into an array and the tail at an index,
|
|
|
|
/// returns `None` if `N` is out of bounds.
|
|
|
|
pub fn try_split_array_at<T, const N: usize>(slice: &[T]) -> Option<(&[T; N], &[T])>
|
|
|
|
where
|
|
|
|
[T; N]: for<'a> TryFrom<&'a [T]>,
|
|
|
|
{
|
|
|
|
let (head, tail) = try_split_at(slice, N)?;
|
|
|
|
let head = head.try_into().ok()?;
|
|
|
|
Some((head, tail))
|
|
|
|
}
|