init profile TOFU features

This commit is contained in:
yggverse 2025-07-23 02:13:10 +03:00
parent 5aa6b1464c
commit f831212d40
11 changed files with 403 additions and 44 deletions

103
src/profile/tofu.rs Normal file
View file

@ -0,0 +1,103 @@
mod certificate;
mod database;
use anyhow::Result;
use certificate::Certificate;
use database::Database;
use gtk::{gio::TlsCertificate, glib::Uri};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use sourceview::prelude::TlsCertificateExt;
use sqlite::Transaction;
use std::sync::RwLock;
/// TOFU wrapper for the Gemini protocol
///
/// https://geminiprotocol.net/docs/protocol-specification.gmi#tls-server-certificate-validation
pub struct Tofu {
database: Database,
memory: RwLock<Vec<Certificate>>,
}
impl Tofu {
// Constructors
pub fn init(database_pool: &Pool<SqliteConnectionManager>, profile_id: i64) -> Result<Self> {
let database = Database::init(database_pool, profile_id);
let records = database.records()?;
let memory = RwLock::new(Vec::with_capacity(records.len()));
{
// build in-memory index...
let mut m = memory.write().unwrap();
for r in records {
m.push(Certificate::from_db(Some(r.id), &r.pem, r.time)?)
}
}
Ok(Self { database, memory })
}
// Actions
pub fn add(&self, tls_certificate: TlsCertificate) -> Result<()> {
self.memory
.write()
.unwrap()
.push(Certificate::from_tls_certificate(tls_certificate)?);
Ok(())
}
pub fn server_certificates(&self, uri: &Uri) -> Option<Vec<TlsCertificate>> {
fn f(subject_name: &str) -> String {
subject_name
.trim_start_matches("CN=")
.trim_start_matches('*')
.trim_matches('.')
.to_lowercase()
}
if let Some(h) = uri.host() {
let k = f(&h);
let m = self.memory.read().unwrap();
let b: Vec<TlsCertificate> = m
.iter()
.filter_map(|certificate| {
let tls_certificate = certificate.tls_certificate();
if k.ends_with(&f(&tls_certificate.subject_name().unwrap())) {
Some(tls_certificate.clone())
} else {
None
}
})
.collect();
if !b.is_empty() {
return Some(b);
}
}
None
}
/// Save in-memory index to the permanent database (on app close)
pub fn save(&self) -> Result<()> {
for c in self.memory.read().unwrap().iter() {
if c.id().is_none() {
self.database.add(c.time(), &c.pem())?;
}
}
Ok(())
}
}
// Tools
pub fn migrate(tx: &Transaction) -> Result<()> {
// Migrate self components
database::init(tx)?;
// Delegate migration to childs
// nothing yet...
// Success
Ok(())
}

View file

@ -0,0 +1,52 @@
use anyhow::Result;
use gtk::{
gio::TlsCertificate,
glib::{DateTime, GString},
};
use sourceview::prelude::TlsCertificateExt;
#[derive(PartialEq, Eq, Hash)]
pub struct Certificate {
id: Option<i64>,
time: DateTime,
tls_certificate: TlsCertificate,
}
impl Certificate {
// Constructors
pub fn from_db(id: Option<i64>, pem: &str, time: DateTime) -> Result<Self> {
Ok(Self {
id,
time,
tls_certificate: TlsCertificate::from_pem(pem)?,
})
}
pub fn from_tls_certificate(tls_certificate: TlsCertificate) -> Result<Self> {
Ok(Self {
id: None,
time: DateTime::now_local()?,
tls_certificate,
})
}
// Getters
pub fn pem(&self) -> GString {
self.tls_certificate.certificate_pem().unwrap()
}
pub fn id(&self) -> Option<i64> {
self.id
}
pub fn time(&self) -> &DateTime {
&self.time
}
pub fn tls_certificate(&self) -> &TlsCertificate {
&self.tls_certificate
}
}

View file

@ -0,0 +1,97 @@
mod row;
use anyhow::Result;
use gtk::glib::DateTime;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use row::Row;
use sqlite::Transaction;
pub struct Database {
pool: Pool<SqliteConnectionManager>,
profile_id: i64,
}
impl Database {
// Constructors
/// Create new `Self`
pub fn init(pool: &Pool<SqliteConnectionManager>, profile_id: i64) -> Self {
Self {
pool: pool.clone(),
profile_id,
}
}
// Getters
/// Get records from database with optional filter by `request`
pub fn records(&self) -> Result<Vec<Row>> {
select(&self.pool.get()?.unchecked_transaction()?, self.profile_id)
}
// Setters
/// Create new record in database
/// * return last insert ID on success
pub fn add(&self, time: &DateTime, pem: &str) -> Result<i64> {
let mut connection = self.pool.get()?;
let tx = connection.transaction()?;
let id = insert(&tx, self.profile_id, time, pem)?;
tx.commit()?;
Ok(id)
}
}
// Low-level DB API
pub fn init(tx: &Transaction) -> Result<usize> {
Ok(tx.execute(
"CREATE TABLE IF NOT EXISTS `profile_tofu`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_id` INTEGER NOT NULL,
`time` INTEGER NOT NULL,
`pem` TEXT NOT NULL,
FOREIGN KEY (`profile_id`) REFERENCES `profile` (`id`)
)",
[],
)?)
}
pub fn insert(tx: &Transaction, profile_id: i64, time: &DateTime, pem: &str) -> Result<i64> {
tx.execute(
"INSERT INTO `profile_tofu` (
`profile_id`,
`time`,
`pem`
) VALUES (?, ?, ?)",
(profile_id, time.to_unix(), pem),
)?;
Ok(tx.last_insert_rowid())
}
pub fn select(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> {
let mut stmt = tx.prepare(
"SELECT `id`, `profile_id`, `time`, `pem` FROM `profile_tofu` WHERE `profile_id` = ?",
)?;
let result = stmt.query_map([profile_id], |row| {
Ok(Row {
id: row.get(0)?,
//profile_id: row.get(1)?,
time: DateTime::from_unix_local(row.get(2)?).unwrap(),
pem: row.get(3)?,
})
})?;
let mut records = Vec::new();
for record in result {
let table = record?;
records.push(table);
}
Ok(records)
}

View file

@ -0,0 +1,5 @@
pub struct Row {
pub id: i64,
pub pem: String,
pub time: gtk::glib::DateTime,
}