1
0
Fork 0
mirror of https://gitlab.com/famedly/conduit.git synced 2025-06-27 16:35:59 +00:00
conduit/src/utils/mod.rs

181 lines
5.7 KiB
Rust
Raw Normal View History

pub mod error;
2020-04-19 14:14:47 +02:00
use argon2::{Config, Variant};
use cmp::Ordering;
use rand::prelude::*;
2022-10-05 18:36:12 +02:00
use ring::digest;
2022-10-09 17:25:06 +02:00
use ruma::{canonical_json::try_from_json_map, CanonicalJsonError, CanonicalJsonObject};
use std::{
2022-01-20 11:51:31 +01:00
cmp, fmt,
2021-04-13 12:15:58 -06:00
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
2020-03-29 13:48:44 +02:00
2020-04-12 21:12:50 +02:00
pub fn millis_since_unix_epoch() -> u64 {
SystemTime::now()
2020-03-29 13:48:44 +02:00
.duration_since(UNIX_EPOCH)
2020-06-09 15:13:17 +02:00
.expect("time is valid")
2020-04-12 21:12:50 +02:00
.as_millis() as u64
2020-03-29 13:48:44 +02:00
}
2020-03-29 21:05:20 +02:00
pub fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
2020-06-09 15:13:17 +02:00
let number = match old.map(|bytes| bytes.try_into()) {
Some(Ok(bytes)) => {
let number = u64::from_be_bytes(bytes);
number + 1
}
2020-06-09 15:13:17 +02:00
_ => 1, // Start at one. since 0 should return the first event in the db
};
2020-03-29 21:05:20 +02:00
Some(number.to_be_bytes().to_vec())
2020-03-29 21:05:20 +02:00
}
2021-06-08 18:10:00 +02:00
pub fn generate_keypair() -> Vec<u8> {
let mut value = random_string(8).as_bytes().to_vec();
value.push(0xff);
value.extend_from_slice(
&ruma::signatures::Ed25519KeyPair::generate()
.expect("Ed25519KeyPair generation always works (?)"),
);
value
2020-04-19 14:14:47 +02:00
}
/// Parses the bytes into an u64.
2020-06-09 15:13:17 +02:00
pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64, std::array::TryFromSliceError> {
let array: [u8; 8] = bytes.try_into()?;
Ok(u64::from_be_bytes(array))
}
/// Parses the bytes into a string.
2020-06-09 15:13:17 +02:00
pub fn string_from_bytes(bytes: &[u8]) -> Result<String, std::string::FromUtf8Error> {
String::from_utf8(bytes.to_vec())
2020-03-29 21:05:20 +02:00
}
pub fn random_string(length: usize) -> String {
thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(length)
.map(char::from)
.collect()
}
/// Calculate a new hash for the given password
2022-10-05 18:36:12 +02:00
pub fn calculate_password_hash(password: &str) -> Result<String, argon2::Error> {
let hashing_config = Config {
variant: Variant::Argon2id,
..Default::default()
};
let salt = random_string(32);
2020-04-19 14:14:47 +02:00
argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &hashing_config)
}
2022-10-05 18:36:12 +02:00
#[tracing::instrument(skip(keys))]
pub fn calculate_hash(keys: &[&[u8]]) -> Vec<u8> {
// We only hash the pdu's event ids, not the whole pdu
let bytes = keys.join(&0xff);
let hash = digest::digest(&digest::SHA256, &bytes);
hash.as_ref().to_owned()
}
2021-04-14 10:43:31 +02:00
pub fn common_elements(
2021-04-09 21:38:16 +02:00
mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>,
check_order: impl Fn(&[u8], &[u8]) -> Ordering,
) -> Option<impl Iterator<Item = Vec<u8>>> {
let first_iterator = iterators.next()?;
let mut other_iterators = iterators.map(|i| i.peekable()).collect::<Vec<_>>();
Some(first_iterator.filter(move |target| {
2021-06-17 20:34:14 +02:00
other_iterators.iter_mut().all(|it| {
while let Some(element) = it.peek() {
match check_order(element, target) {
Ordering::Greater => return false, // We went too far
Ordering::Equal => return true, // Element is in both iters
Ordering::Less => {
// Keep searching
it.next();
}
}
2021-06-17 20:34:14 +02:00
}
false
})
}))
}
/// Fallible conversion from any value that implements `Serialize` to a `CanonicalJsonObject`.
///
/// `value` must serialize to an `serde_json::Value::Object`.
pub fn to_canonical_object<T: serde::Serialize>(
value: T,
) -> Result<CanonicalJsonObject, CanonicalJsonError> {
use serde::ser::Error;
match serde_json::to_value(value).map_err(CanonicalJsonError::SerDe)? {
serde_json::Value::Object(map) => try_from_json_map(map),
_ => Err(CanonicalJsonError::SerDe(serde_json::Error::custom(
"Value must be an object",
))),
}
}
2021-04-13 12:15:58 -06:00
pub fn deserialize_from_str<
'de,
D: serde::de::Deserializer<'de>,
T: FromStr<Err = E>,
E: fmt::Display,
2021-04-13 12:15:58 -06:00
>(
deserializer: D,
) -> Result<T, D::Error> {
2021-04-13 12:15:58 -06:00
struct Visitor<T: FromStr<Err = E>, E>(std::marker::PhantomData<T>);
impl<'de, T: FromStr<Err = Err>, Err: fmt::Display> serde::de::Visitor<'de> for Visitor<T, Err> {
2021-04-13 12:15:58 -06:00
type Value = T;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2021-04-13 12:15:58 -06:00
write!(formatter, "a parsable string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
v.parse().map_err(serde::de::Error::custom)
2021-04-13 12:15:58 -06:00
}
}
deserializer.deserialize_str(Visitor(std::marker::PhantomData))
}
2022-01-20 11:51:31 +01:00
// Copied from librustdoc:
// https://github.com/rust-lang/rust/blob/cbaeec14f90b59a91a6b0f17fc046c66fa811892/src/librustdoc/html/escape.rs
/// Wrapper struct which will emit the HTML-escaped version of the contained
/// string when passed to a format string.
pub struct HtmlEscape<'a>(pub &'a str);
impl<'a> fmt::Display for HtmlEscape<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let HtmlEscape(s) = *self;
let pile_o_bits = s;
let mut last = 0;
for (i, ch) in s.char_indices() {
let s = match ch {
'>' => "&gt;",
'<' => "&lt;",
'&' => "&amp;",
'\'' => "&#39;",
'"' => "&quot;",
_ => continue,
};
fmt.write_str(&pile_o_bits[last..i])?;
fmt.write_str(s)?;
// NOTE: we only expect single byte characters here - which is fine as long as we
// only match single byte characters
last = i + 1;
}
if last < s.len() {
fmt.write_str(&pile_o_bits[last..])?;
}
Ok(())
}
}