database: added keys migration, get/insert, insert keys at launch if none are present

This commit is contained in:
Philippe Loctaux 2023-03-12 18:45:55 +01:00
parent 7f11016a34
commit 8c37fc1181
15 changed files with 453 additions and 2 deletions

View file

@ -10,6 +10,8 @@ serde = { workspace = true }
serde_json = { workspace = true }
rand = "0.8.5"
rsa = "0.7.2"
chrono = { workspace = true }
# local crates
id = { path = "../id" }
database = { path = "../database" }

View file

@ -0,0 +1,76 @@
use crate::{Error, PrivateKey, PublicKey};
use chrono::{DateTime, Utc};
use database::sqlx::SqliteExecutor;
use database::Keys as DatabaseKeys;
use id::KeyID;
pub async fn save_new_keys(
conn: impl SqliteExecutor<'_>,
id: &KeyID,
private: &PrivateKey,
public: &PublicKey,
) -> Result<Option<()>, Error> {
Ok(DatabaseKeys::insert(
conn,
&id.0,
private.to_der()?.as_slice(),
public.to_der()?.as_slice(),
)
.await?)
}
#[derive(Debug)]
pub struct Key {
id: KeyID,
created_at: DateTime<Utc>,
revoked_at: Option<DateTime<Utc>>,
private_der: Vec<u8>,
public_der: Vec<u8>,
}
impl Key {
pub fn key_id(&self) -> &KeyID {
&self.id
}
pub fn created_at(&self) -> DateTime<Utc> {
self.created_at
}
pub fn private_der(&self) -> &[u8] {
&self.private_der
}
pub fn public_der(&self) -> &[u8] {
&self.public_der
}
}
impl From<DatabaseKeys> for Key {
fn from(db: DatabaseKeys) -> Self {
Self {
id: KeyID(db.id),
created_at: db.created_at,
revoked_at: db.revoked_at,
private_der: db.private_der,
public_der: db.public_der,
}
}
}
impl Key {
pub async fn get_most_recent(conn: impl SqliteExecutor<'_>) -> Result<Option<Self>, Error> {
Ok(DatabaseKeys::get_most_recent(conn).await?.map(Self::from))
}
pub async fn get_all(
conn: impl SqliteExecutor<'_>,
filter_get_revoked: Option<bool>,
) -> Result<Vec<Self>, Error> {
Ok(DatabaseKeys::get_all(conn, filter_get_revoked)
.await?
.into_iter()
.map(Self::from)
.collect::<Vec<_>>())
}
}

View file

@ -3,6 +3,9 @@
// the rest
#[derive(Debug)]
pub enum Error {
#[error("Database: {0}")]
Database(#[from] database::Error),
#[error("Failed to generate key: `{0}`")]
Generation(#[from] rsa::errors::Error),

View file

@ -1,5 +1,6 @@
extern crate core;
pub mod database;
mod error;
mod jwk;
mod key;