add request verification extractor

This commit is contained in:
sam 2024-01-18 16:34:40 +01:00
parent 7a694623e5
commit 1e53661b0a
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
18 changed files with 482 additions and 32 deletions

50
chat/src/db/mod.rs Normal file
View file

@ -0,0 +1,50 @@
use eyre::{OptionExt, Result};
use rsa::pkcs1::{EncodeRsaPrivateKey, EncodeRsaPublicKey, LineEnding};
use rsa::{RsaPrivateKey, RsaPublicKey};
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres};
use std::time::Duration;
pub async fn init(dsn: &str) -> Result<Pool<Postgres>> {
let pool = PgPoolOptions::new()
.acquire_timeout(Duration::from_secs(2)) // Fail fast and don't hang
.max_connections(100)
.connect(dsn)
.await?;
Ok(pool)
}
const PRIVATE_KEY_BITS: usize = 2048;
pub async fn init_instance(pool: &Pool<Postgres>) -> Result<()> {
let mut tx = pool.begin().await?;
// Check if we already have an instance configuration
let row = sqlx::query!("select exists(select * from instance)")
.fetch_one(&mut *tx)
.await?;
if row.exists.ok_or_eyre("exists was null")? {
return Ok(());
}
// Generate public/private key
let mut rng = rand::thread_rng();
let priv_key = RsaPrivateKey::new(&mut rng, PRIVATE_KEY_BITS)?;
let pub_key = RsaPublicKey::from(&priv_key);
let priv_key_string = priv_key.to_pkcs1_pem(LineEnding::LF)?;
let pub_key_string = pub_key.to_pkcs1_pem(LineEnding::LF)?;
sqlx::query!(
"insert into instance (public_key, private_key) values ($1, $2)",
pub_key_string,
priv_key_string.to_string(),
)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}