make multi-protocol identity feature

This commit is contained in:
yggverse 2025-01-23 10:57:12 +02:00
parent 92550a2ccc
commit 12d79792d9
33 changed files with 309 additions and 593 deletions

View file

@ -164,7 +164,6 @@ fn handle(
.page .page
.profile .profile
.identity .identity
.gemini
.match_scope(&uri.to_string()) .match_scope(&uri.to_string())
{ {
Some(identity) => match identity.to_tls_certificate() { Some(identity) => match identity.to_tls_certificate() {

View file

@ -42,25 +42,20 @@ impl Gemini {
move |response| { move |response| {
// Get option match user choice // Get option match user choice
let option = match response { let option = match response {
Value::ProfileIdentityGeminiId(value) => Some(value), Value::ProfileIdentityId(value) => Some(value),
Value::GuestSession => None, Value::GuestSession => None,
Value::GeneratePem => Some( Value::GeneratePem => Some(
match profile match profile
.identity .identity
.gemini
.make(None, &widget.form.name.value().unwrap()) .make(None, &widget.form.name.value().unwrap())
{ {
Ok(profile_identity_gemini_id) => profile_identity_gemini_id, Ok(profile_identity_id) => profile_identity_id,
Err(e) => todo!("{}", e.to_string()), Err(e) => todo!("{}", e.to_string()),
}, },
), ),
Value::ImportPem => Some( Value::ImportPem => Some(
match profile match profile.identity.add(&widget.form.file.pem.take().unwrap()) {
.identity Ok(profile_identity_id) => profile_identity_id,
.gemini
.add(&widget.form.file.pem.take().unwrap())
{
Ok(profile_identity_gemini_id) => profile_identity_gemini_id,
Err(e) => todo!("{}", e.to_string()), Err(e) => todo!("{}", e.to_string()),
}, },
), ),
@ -69,19 +64,15 @@ impl Gemini {
// Apply auth // Apply auth
match option { match option {
// Activate identity for `auth_uri` // Activate identity for `auth_uri`
Some(profile_identity_gemini_id) => { Some(profile_identity_id) => {
if let Err(e) = profile if let Err(e) = profile.identity.auth.apply(profile_identity_id, &auth_url)
.identity
.gemini
.auth
.apply(profile_identity_gemini_id, &auth_url)
{ {
todo!("{}", e.to_string()) todo!("{}", e.to_string())
}; };
} }
// Remove all identity auths for `auth_uri` // Remove all identity auths for `auth_uri`
None => { None => {
if let Err(e) = profile.identity.gemini.auth.remove_scope(&auth_url) { if let Err(e) = profile.identity.auth.remove_scope(&auth_url) {
todo!("{}", e.to_string()) todo!("{}", e.to_string())
}; };
} }

View file

@ -104,19 +104,16 @@ impl Form {
self.file.update(matches!(value, Value::ImportPem)); self.file.update(matches!(value, Value::ImportPem));
match value { match value {
Value::ProfileIdentityGeminiId(profile_identity_gemini_id) => { Value::ProfileIdentityId(profile_identity_id) => {
self.drop.update(true); self.drop.update(true);
self.exit.update( self.exit.update(
true, true,
self.profile self.profile
.identity .identity
.gemini
.auth .auth
.memory .memory
.match_scope(&self.auth_uri.to_string()) .match_scope(&self.auth_uri.to_string())
.is_some_and(|auth| { .is_some_and(|auth| auth.profile_identity_id == profile_identity_id),
auth.profile_identity_gemini_id == profile_identity_gemini_id
}),
); );
self.save.update(true); self.save.update(true);
} }

View file

@ -45,7 +45,7 @@ impl Drop {
let profile = profile.clone(); let profile = profile.clone();
move |_| { move |_| {
match list.selected().value_enum() { match list.selected().value_enum() {
Value::ProfileIdentityGeminiId(profile_identity_gemini_id) => { Value::ProfileIdentityId(profile_identity_id) => {
// Init sub-widget // Init sub-widget
let alert_dialog = AlertDialog::builder() let alert_dialog = AlertDialog::builder()
.heading(HEADING) .heading(HEADING)
@ -74,13 +74,9 @@ impl Drop {
let button = button.clone(); let button = button.clone();
let list = list.clone(); let list = list.clone();
let profile = profile.clone(); let profile = profile.clone();
move |_, _| match profile move |_, _| match profile.identity.delete(profile_identity_id) {
.identity
.gemini
.delete(profile_identity_gemini_id)
{
Ok(_) => { Ok(_) => {
if list.remove(profile_identity_gemini_id).is_some() { if list.remove(profile_identity_id).is_some() {
button.set_css_classes(&["success"]); button.set_css_classes(&["success"]);
button.set_label("Identity successfully deleted") button.set_label("Identity successfully deleted")
} else { } else {

View file

@ -58,7 +58,7 @@ impl Exit {
move |_| { move |_| {
// Get selected identity from holder // Get selected identity from holder
match list.selected().value_enum() { match list.selected().value_enum() {
Value::ProfileIdentityGeminiId(profile_identity_gemini_id) => { Value::ProfileIdentityId(profile_identity_id) => {
// Init sub-widget // Init sub-widget
let alert_dialog = AlertDialog::builder() let alert_dialog = AlertDialog::builder()
.heading(HEADING) .heading(HEADING)
@ -91,12 +91,7 @@ impl Exit {
let browser_action = browser_action.clone(); let browser_action = browser_action.clone();
let widget_action = widget_action.clone(); let widget_action = widget_action.clone();
move |_, _| { move |_, _| {
match profile match profile.identity.auth.remove_ref(profile_identity_id) {
.identity
.gemini
.auth
.remove_ref(profile_identity_gemini_id)
{
Ok(_) => match list Ok(_) => match list
.selected() .selected()
.update(&profile, &auth_uri.to_string()) .update(&profile, &auth_uri.to_string())

View file

@ -38,15 +38,12 @@ impl List {
list_store.append(&generate_pem); list_store.append(&generate_pem);
list_store.append(&import_pem); list_store.append(&import_pem);
match profile.identity.gemini.database.records() { match profile.identity.database.records() {
Ok(identities) => { Ok(identities) => {
let mut is_guest_session = true; let mut is_guest_session = true;
for identity in identities { for identity in identities {
match Item::new_profile_identity_gemini_id( match Item::new_profile_identity_id(profile, identity.id, &auth_uri.to_string())
profile, {
identity.id,
&auth_uri.to_string(),
) {
Ok(item) => { Ok(item) => {
if item.is_active() { if item.is_active() {
is_guest_session = false; is_guest_session = false;
@ -178,18 +175,18 @@ impl List {
// Actions // Actions
/// Find list item by `profile_identity_gemini_id` /// Find list item by `profile_identity_id`
/// * return `position` found /// * return `position` found
pub fn find(&self, profile_identity_gemini_id: i64) -> Option<u32> { pub fn find(&self, profile_identity_id: i64) -> Option<u32> {
self.list_store.find_with_equal_func(|this| { self.list_store.find_with_equal_func(|this| {
profile_identity_gemini_id == this.downcast_ref::<Item>().unwrap().value() profile_identity_id == this.downcast_ref::<Item>().unwrap().value()
}) })
} }
/// Remove list item by `profile_identity_gemini_id` /// Remove list item by `profile_identity_id`
/// * return `position` of removed list item /// * return `position` of removed list item
pub fn remove(&self, profile_identity_gemini_id: i64) -> Option<u32> { pub fn remove(&self, profile_identity_id: i64) -> Option<u32> {
match self.find(profile_identity_gemini_id) { match self.find(profile_identity_id) {
Some(position) => { Some(position) => {
self.list_store.remove(position); self.list_store.remove(position);
Some(position) Some(position)

View file

@ -21,7 +21,7 @@ glib::wrapper! {
} }
// C-type property `value` conversion for `Item` // C-type property `value` conversion for `Item`
// * values > 0 reserved for `profile_identity_gemini_id` // * values > 0 reserved for `profile_identity_id`
const G_VALUE_GENERATE_PEM: i64 = 0; const G_VALUE_GENERATE_PEM: i64 = 0;
const G_VALUE_IMPORT_PEM: i64 = -1; const G_VALUE_IMPORT_PEM: i64 = -1;
const G_VALUE_GUEST_SESSION: i64 = -2; const G_VALUE_GUEST_SESSION: i64 = -2;
@ -53,42 +53,34 @@ impl Item {
.build() .build()
} }
pub fn new_profile_identity_gemini_id( pub fn new_profile_identity_id(
profile: &Rc<Profile>, profile: &Rc<Profile>,
profile_identity_gemini_id: i64, profile_identity_id: i64,
auth_url: &str, auth_url: &str,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
// Get PEM by ID // Get PEM by ID
match profile match profile.identity.memory.get(profile_identity_id) {
.identity
.gemini
.memory
.get(profile_identity_gemini_id)
{
// Extract certificate details from PEM string // Extract certificate details from PEM string
Ok(ref pem) => match TlsCertificate::from_pem(pem) { Ok(ref pem) => match TlsCertificate::from_pem(pem) {
// Collect certificate scopes for item // Collect certificate scopes for item
Ok(ref certificate) => match scope(profile, profile_identity_gemini_id) { Ok(ref certificate) => match scope(profile, profile_identity_id) {
// Ready to build `Item` GObject // Ready to build `Item` GObject
Ok(ref scope) => Ok(Object::builder() Ok(ref scope) => Ok(Object::builder()
.property("value", profile_identity_gemini_id) .property("value", profile_identity_id)
.property( .property("title", title::new_for_profile_identity_id(certificate))
"title",
title::new_for_profile_identity_gemini_id(certificate),
)
.property( .property(
"subtitle", "subtitle",
subtitle::new_for_profile_identity_gemini_id(certificate, scope), subtitle::new_for_profile_identity_id(certificate, scope),
) )
.property( .property(
"tooltip", "tooltip",
tooltip::new_for_profile_identity_gemini_id(certificate, scope), tooltip::new_for_profile_identity_id(certificate, scope),
) )
.property( .property(
"is-active", "is-active",
is_active::new_for_profile_identity_gemini_id( is_active::new_for_profile_identity_id(
profile, profile,
profile_identity_gemini_id, profile_identity_id,
auth_url, auth_url,
), ),
) )
@ -107,36 +99,31 @@ impl Item {
pub fn update(&self, profile: &Rc<Profile>, auth_url: &str) -> Result<(), Error> { pub fn update(&self, profile: &Rc<Profile>, auth_url: &str) -> Result<(), Error> {
// Update item depending on value type // Update item depending on value type
match self.value_enum() { match self.value_enum() {
Value::ProfileIdentityGeminiId(profile_identity_gemini_id) => { Value::ProfileIdentityId(profile_identity_id) => {
// Get PEM by ID // Get PEM by ID
match profile match profile.identity.memory.get(profile_identity_id) {
.identity
.gemini
.memory
.get(profile_identity_gemini_id)
{
// Extract certificate details from PEM string // Extract certificate details from PEM string
Ok(ref pem) => match TlsCertificate::from_pem(pem) { Ok(ref pem) => match TlsCertificate::from_pem(pem) {
Ok(ref certificate) => { Ok(ref certificate) => {
// Get current scope // Get current scope
let scope = &scope(profile, profile_identity_gemini_id)?; let scope = &scope(profile, profile_identity_id)?;
// Update properties // Update properties
self.set_title(title::new_for_profile_identity_gemini_id(certificate)); self.set_title(title::new_for_profile_identity_id(certificate));
self.set_subtitle(subtitle::new_for_profile_identity_gemini_id( self.set_subtitle(subtitle::new_for_profile_identity_id(
certificate, certificate,
scope, scope,
)); ));
self.set_tooltip(tooltip::new_for_profile_identity_gemini_id( self.set_tooltip(tooltip::new_for_profile_identity_id(
certificate, certificate,
scope, scope,
)); ));
self.set_is_active(is_active::new_for_profile_identity_gemini_id( self.set_is_active(is_active::new_for_profile_identity_id(
profile, profile,
profile_identity_gemini_id, profile_identity_id,
auth_url, auth_url,
)); ));
@ -162,21 +149,21 @@ impl Item {
G_VALUE_GENERATE_PEM => Value::GeneratePem, G_VALUE_GENERATE_PEM => Value::GeneratePem,
G_VALUE_GUEST_SESSION => Value::GuestSession, G_VALUE_GUEST_SESSION => Value::GuestSession,
G_VALUE_IMPORT_PEM => Value::ImportPem, G_VALUE_IMPORT_PEM => Value::ImportPem,
value => Value::ProfileIdentityGeminiId(value), value => Value::ProfileIdentityId(value),
} }
} }
} }
// Tools // Tools
/// Collect certificate scope vector from `Profile` database for `profile_identity_gemini_id` /// Collect certificate scope vector from `Profile` database for `profile_identity_id`
fn scope(profile: &Rc<Profile>, profile_identity_gemini_id: i64) -> Result<Vec<String>, Error> { fn scope(profile: &Rc<Profile>, profile_identity_id: i64) -> Result<Vec<String>, Error> {
match profile.identity.gemini.auth.database.records_scope(None) { match profile.identity.auth.database.records_scope(None) {
Ok(result) => { Ok(result) => {
let mut scope = Vec::new(); let mut scope = Vec::new();
for auth in result for auth in result
.iter() .iter()
.filter(|this| this.profile_identity_gemini_id == profile_identity_gemini_id) .filter(|this| this.profile_identity_id == profile_identity_id)
{ {
scope.push(auth.scope.clone()) scope.push(auth.scope.clone())
} }

View file

@ -1,16 +1,15 @@
use crate::profile::Profile; use crate::profile::Profile;
use std::rc::Rc; use std::rc::Rc;
pub fn new_for_profile_identity_gemini_id( pub fn new_for_profile_identity_id(
profile: &Rc<Profile>, profile: &Rc<Profile>,
profile_identity_gemini_id: i64, profile_identity_id: i64,
auth_url: &str, auth_url: &str,
) -> bool { ) -> bool {
profile profile
.identity .identity
.gemini
.auth .auth
.memory .memory
.match_scope(auth_url) .match_scope(auth_url)
.is_some_and(|auth| auth.profile_identity_gemini_id == profile_identity_gemini_id) .is_some_and(|auth| auth.profile_identity_id == profile_identity_id)
} }

View file

@ -2,10 +2,7 @@ use gtk::{gio::TlsCertificate, prelude::TlsCertificateExt};
const DATE_FORMAT: &str = "%Y.%m.%d"; const DATE_FORMAT: &str = "%Y.%m.%d";
pub fn new_for_profile_identity_gemini_id( pub fn new_for_profile_identity_id(certificate: &TlsCertificate, scope: &[String]) -> String {
certificate: &TlsCertificate,
scope: &[String],
) -> String {
format!( format!(
"{} - {} | scope: {}", "{} - {} | scope: {}",
certificate certificate

View file

@ -1,6 +1,6 @@
use gtk::{gio::TlsCertificate, glib::gformat, prelude::TlsCertificateExt}; use gtk::{gio::TlsCertificate, glib::gformat, prelude::TlsCertificateExt};
pub fn new_for_profile_identity_gemini_id(certificate: &TlsCertificate) -> String { pub fn new_for_profile_identity_id(certificate: &TlsCertificate) -> String {
certificate certificate
.subject_name() .subject_name()
.unwrap_or(gformat!("Unknown")) .unwrap_or(gformat!("Unknown"))

View file

@ -1,9 +1,6 @@
use gtk::{gio::TlsCertificate, prelude::TlsCertificateExt}; use gtk::{gio::TlsCertificate, prelude::TlsCertificateExt};
pub fn new_for_profile_identity_gemini_id( pub fn new_for_profile_identity_id(certificate: &TlsCertificate, scope: &[String]) -> String {
certificate: &TlsCertificate,
scope: &[String],
) -> String {
let mut tooltip = "<b>Certificate</b>\n".to_string(); let mut tooltip = "<b>Certificate</b>\n".to_string();
if let Some(subject_name) = certificate.subject_name() { if let Some(subject_name) = certificate.subject_name() {

View file

@ -3,5 +3,5 @@ pub enum Value {
GeneratePem, GeneratePem,
GuestSession, GuestSession,
ImportPem, ImportPem,
ProfileIdentityGeminiId(i64), ProfileIdentityId(i64),
} }

View file

@ -40,12 +40,12 @@ impl Save {
move |_| { move |_| {
// Get selected identity from holder // Get selected identity from holder
match list.selected().value_enum() { match list.selected().value_enum() {
Value::ProfileIdentityGeminiId(profile_identity_gemini_id) => { Value::ProfileIdentityId(profile_identity_id) => {
// Lock open button (prevent double click) // Lock open button (prevent double click)
button.set_sensitive(false); button.set_sensitive(false);
// Create PEM file based on option ID selected // Create PEM file based on option ID selected
match Certificate::new(profile.clone(), profile_identity_gemini_id) { match Certificate::new(profile.clone(), profile_identity_id) {
Ok(certificate) => { Ok(certificate) => {
// Init file filters related with PEM extension // Init file filters related with PEM extension
let filters = ListStore::new::<FileFilter>(); let filters = ListStore::new::<FileFilter>();

View file

@ -15,13 +15,8 @@ impl Certificate {
// Constructors // Constructors
/// Create new `Self` /// Create new `Self`
pub fn new(profile: Rc<Profile>, profile_identity_gemini_id: i64) -> Result<Self, Error> { pub fn new(profile: Rc<Profile>, profile_identity_id: i64) -> Result<Self, Error> {
match profile match profile.identity.database.record(profile_identity_id) {
.identity
.gemini
.database
.record(profile_identity_gemini_id)
{
Ok(record) => match record { Ok(record) => match record {
Some(identity) => match TlsCertificate::from_pem(&identity.pem) { Some(identity) => match TlsCertificate::from_pem(&identity.pem) {
Ok(certificate) => Ok(Self { Ok(certificate) => Ok(Self {
@ -30,7 +25,7 @@ impl Certificate {
}), }),
Err(e) => Err(Error::TlsCertificate(e)), Err(e) => Err(Error::TlsCertificate(e)),
}, },
None => Err(Error::NotFound(profile_identity_gemini_id)), None => Err(Error::NotFound(profile_identity_id)),
}, },
Err(e) => Err(Error::Database(e)), Err(e) => Err(Error::Database(e)),
} }

View file

@ -14,8 +14,8 @@ impl Display for Error {
Self::Database(e) => { Self::Database(e) => {
write!(f, "Database error: {e}") write!(f, "Database error: {e}")
} }
Self::NotFound(profile_identity_gemini_id) => { Self::NotFound(profile_identity_id) => {
write!(f, "Record for `{profile_identity_gemini_id}` not found") write!(f, "Record for `{profile_identity_id}` not found")
} }
Self::TlsCertificate(e) => { Self::TlsCertificate(e) => {
write!(f, "TLS certificate error: {e}") write!(f, "TLS certificate error: {e}")

View file

@ -79,7 +79,6 @@ impl Navigation {
self.request.update( self.request.update(
self.profile self.profile
.identity .identity
.gemini
.auth .auth
.memory .memory
.match_scope(&request) .match_scope(&request)

View file

@ -1,51 +1,144 @@
mod auth;
mod certificate;
mod database; mod database;
mod error; mod error;
mod gemini; mod item;
mod memory;
use auth::Auth;
use database::Database; use database::Database;
pub use error::Error; pub use error::Error;
use gemini::Gemini; use item::Item;
use memory::Memory;
use gtk::glib::DateTime;
use sqlite::{Connection, Transaction}; use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock}; use std::{rc::Rc, sync::RwLock};
/// Authorization wrapper for different protocols /// Authorization wrapper for Gemini protocol
///
/// https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates
pub struct Identity { pub struct Identity {
// database: Rc<Database>, pub auth: Rc<Auth>,
pub gemini: Rc<Gemini>, pub database: Rc<Database>,
pub memory: Rc<Memory>,
} }
impl Identity { impl Identity {
// Constructors // Constructors
/// Create new `Self` /// Create new `Self`
pub fn build(connection: &Rc<RwLock<Connection>>, profile_id: &Rc<i64>) -> Result<Self, Error> { pub fn build(
// Init identity database connection: &Rc<RwLock<Connection>>,
let database = Rc::new(Database::build(connection)); profile_identity_id: &Rc<i64>,
) -> Result<Self, Error> {
// Init components
let auth = match Auth::new(connection) {
Ok(auth) => Rc::new(auth),
Err(e) => return Err(Error::Auth(e)),
};
let database = Rc::new(Database::build(connection, profile_identity_id));
let memory = Rc::new(Memory::new());
// Get active identity set for profile or create new one // Init `Self`
let profile_identity_id = Rc::new(match database.active() { let this = Self {
Ok(result) => match result { auth,
Some(identity) => identity.id, database,
None => match database.add(profile_id, true) { memory,
Ok(id) => id, };
Err(e) => return Err(Error::Database(e)),
}, // Build initial index
Self::index(&this)?;
Ok(this)
}
// Actions
/// Add new record to database, update memory index
/// * return new `profile_identity_id` on success
pub fn add(&self, pem: &str) -> Result<i64, Error> {
match self.database.add(pem) {
Ok(profile_identity_id) => {
self.index()?;
Ok(profile_identity_id)
}
Err(e) => Err(Error::Database(e)),
}
}
/// Delete record from database including children dependencies, update memory index
pub fn delete(&self, profile_identity_id: i64) -> Result<(), Error> {
match self.auth.remove_ref(profile_identity_id) {
Ok(_) => match self.database.delete(profile_identity_id) {
Ok(_) => {
self.index()?;
Ok(())
}
Err(e) => Err(Error::Database(e)),
}, },
Err(e) => Err(Error::Auth(e)),
}
}
/// Generate new certificate and insert record to DB, update memory index
/// * return new `profile_identity_id` on success
pub fn make(&self, time: Option<(DateTime, DateTime)>, name: &str) -> Result<i64, Error> {
// Generate new certificate
match certificate::generate(
match time {
Some(value) => value,
None => (
DateTime::now_local().unwrap(),
DateTime::from_local(9999, 12, 31, 23, 59, 59.9).unwrap(), // max @TODO
),
},
name,
) {
Ok(pem) => self.add(&pem),
Err(e) => Err(Error::Certificate(e)),
}
}
/// Create new `Memory` index from `Database` for `Self`
pub fn index(&self) -> Result<(), Error> {
// Clear previous records
if let Err(e) = self.memory.clear() {
return Err(Error::Memory(e));
}
// Build new index
match self.database.records() {
Ok(records) => {
for record in records {
if let Err(e) = self.memory.add(record.id, record.pem) {
return Err(Error::Memory(e));
}
}
}
Err(e) => return Err(Error::Database(e)), Err(e) => return Err(Error::Database(e)),
}); };
// Init gemini component Ok(())
let gemini = Rc::new(match Gemini::build(connection, &profile_identity_id) { }
Ok(result) => result,
Err(e) => return Err(Error::Gemini(e)),
});
// Done /// Get `Identity` match `request`
Ok(Self { /// * [Client certificates specification](https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates)
// database, /// * this function work with memory cache (not database)
gemini, pub fn match_scope(&self, request: &str) -> Option<Item> {
}) if let Some(auth) = self.auth.memory.match_scope(request) {
match self.memory.get(auth.profile_identity_id) {
Ok(pem) => {
return Some(Item {
// scope: auth.scope,
pem,
});
}
Err(e) => todo!("{:?}", e.to_string()),
}
}
None
} }
} }
@ -58,7 +151,7 @@ pub fn migrate(tx: &Transaction) -> Result<(), String> {
} }
// Delegate migration to childs // Delegate migration to childs
gemini::migrate(tx)?; auth::migrate(tx)?;
// Success // Success
Ok(()) Ok(())

View file

@ -11,7 +11,7 @@ use memory::Memory;
use sqlite::{Connection, Transaction}; use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock}; use std::{rc::Rc, sync::RwLock};
/// API for `profile_identity_gemini_id` + `scope` auth pairs operations /// API for `profile_identity_id` + `scope` auth pairs operations
pub struct Auth { pub struct Auth {
pub database: Rc<Database>, pub database: Rc<Database>,
pub memory: Rc<Memory>, pub memory: Rc<Memory>,
@ -37,26 +37,25 @@ impl Auth {
// Actions // Actions
/// Apply `profile_identity_gemini_id` certificate as the auth for `scope` /// Apply `profile_identity_id` certificate as the auth for `scope`
/// * deactivate active auth by remove previous records from `Self` database /// * deactivate active auth by remove previous records from `Self` database
/// * reindex `Self` memory index on success /// * reindex `Self` memory index on success
/// * return last insert `profile_identity_gemini_auth_id` on success /// * return last insert `profile_identity_auth_id` on success
pub fn apply(&self, profile_identity_gemini_id: i64, scope: &str) -> Result<i64, Error> { pub fn apply(&self, profile_identity_id: i64, scope: &str) -> Result<i64, Error> {
// Cleanup records match `scope` (unauthorize) // Cleanup records match `scope` (unauthorize)
self.remove_scope(scope)?; self.remove_scope(scope)?;
// Create new record (auth) // Create new record (auth)
let profile_identity_gemini_auth_id = let profile_identity_auth_id = match self.database.add(profile_identity_id, scope) {
match self.database.add(profile_identity_gemini_id, scope) { Ok(id) => id,
Ok(id) => id, Err(e) => return Err(Error::Database(e)),
Err(e) => return Err(Error::Database(e)), };
};
// Reindex // Reindex
self.index()?; self.index()?;
// Done // Done
Ok(profile_identity_gemini_auth_id) Ok(profile_identity_auth_id)
} }
/// Remove all records match request (unauthorize) /// Remove all records match request (unauthorize)
@ -75,9 +74,9 @@ impl Auth {
Ok(()) Ok(())
} }
/// Remove all records match `profile_identity_gemini_id` foreign reference key /// Remove all records match `profile_identity_id` foreign reference key
pub fn remove_ref(&self, profile_identity_gemini_id: i64) -> Result<(), Error> { pub fn remove_ref(&self, profile_identity_id: i64) -> Result<(), Error> {
match self.database.records_ref(profile_identity_gemini_id) { match self.database.records_ref(profile_identity_id) {
Ok(records) => { Ok(records) => {
for record in records { for record in records {
if let Err(e) = self.database.delete(record.id) { if let Err(e) = self.database.delete(record.id) {
@ -102,10 +101,7 @@ impl Auth {
match self.database.records_scope(None) { match self.database.records_scope(None) {
Ok(records) => { Ok(records) => {
for record in records { for record in records {
if let Err(e) = self if let Err(e) = self.memory.add(record.scope, record.profile_identity_id) {
.memory
.add(record.scope, record.profile_identity_gemini_id)
{
return Err(Error::Memory(e)); return Err(Error::Memory(e));
} }
} }

View file

@ -3,11 +3,11 @@ use std::{rc::Rc, sync::RwLock};
pub struct Table { pub struct Table {
pub id: i64, pub id: i64,
pub profile_identity_gemini_id: i64, pub profile_identity_id: i64,
pub scope: String, pub scope: String,
} }
/// Storage for `profile_identity_gemini_id` + `scope` auth pairs /// Storage for `profile_identity_id` + `scope` auth pairs
pub struct Database { pub struct Database {
connection: Rc<RwLock<Connection>>, connection: Rc<RwLock<Connection>>,
} }
@ -25,13 +25,13 @@ impl Database {
// Actions // Actions
/// Create new record in database /// Create new record in database
pub fn add(&self, profile_identity_gemini_id: i64, scope: &str) -> Result<i64, Error> { pub fn add(&self, profile_identity_id: i64, scope: &str) -> Result<i64, Error> {
// Begin new transaction // Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?; let tx = writable.transaction()?;
// Create new record // Create new record
insert(&tx, profile_identity_gemini_id, scope)?; insert(&tx, profile_identity_id, scope)?;
// Hold insert ID for result // Hold insert ID for result
let id = last_insert_id(&tx); let id = last_insert_id(&tx);
@ -69,10 +69,10 @@ impl Database {
} }
/// Get records from database match current `profile_id` optionally filtered by `scope` /// Get records from database match current `profile_id` optionally filtered by `scope`
pub fn records_ref(&self, profile_identity_gemini_id: i64) -> Result<Vec<Table>, Error> { pub fn records_ref(&self, profile_identity_id: i64) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap(); // @TODO let readable = self.connection.read().unwrap(); // @TODO
let tx = readable.unchecked_transaction()?; let tx = readable.unchecked_transaction()?;
select_ref(&tx, profile_identity_gemini_id) select_ref(&tx, profile_identity_id)
} }
} }
@ -80,54 +80,47 @@ impl Database {
pub fn init(tx: &Transaction) -> Result<usize, Error> { pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute( tx.execute(
"CREATE TABLE IF NOT EXISTS `profile_identity_gemini_auth` "CREATE TABLE IF NOT EXISTS `profile_identity_auth`
( (
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_identity_gemini_id` INTEGER NOT NULL, `profile_identity_id` INTEGER NOT NULL,
`scope` VARCHAR(1024) NOT NULL, `scope` VARCHAR(1024) NOT NULL,
FOREIGN KEY (`profile_identity_gemini_id`) REFERENCES `profile_identity_gemini`(`id`), FOREIGN KEY (`profile_identity_id`) REFERENCES `profile_identity`(`id`),
UNIQUE (`scope`) UNIQUE (`scope`)
)", )",
[], [],
) )
} }
pub fn insert( pub fn insert(tx: &Transaction, profile_identity_id: i64, scope: &str) -> Result<usize, Error> {
tx: &Transaction,
profile_identity_gemini_id: i64,
scope: &str,
) -> Result<usize, Error> {
tx.execute( tx.execute(
"INSERT INTO `profile_identity_gemini_auth` ( "INSERT INTO `profile_identity_auth` (
`profile_identity_gemini_id`, `profile_identity_id`,
`scope` `scope`
) VALUES (?, ?)", ) VALUES (?, ?)",
(profile_identity_gemini_id, scope), (profile_identity_id, scope),
) )
} }
pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> { pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> {
tx.execute( tx.execute("DELETE FROM `profile_identity_auth` WHERE `id` = ?", [id])
"DELETE FROM `profile_identity_gemini_auth` WHERE `id` = ?",
[id],
)
} }
pub fn select_scope(tx: &Transaction, scope: Option<&str>) -> Result<Vec<Table>, Error> { pub fn select_scope(tx: &Transaction, scope: Option<&str>) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare( let mut stmt = tx.prepare(
"SELECT `id`, "SELECT `id`,
`profile_identity_gemini_id`, `profile_identity_id`,
`scope` `scope`
FROM `profile_identity_gemini_auth` FROM `profile_identity_auth`
WHERE `scope` LIKE ?", WHERE `scope` LIKE ?",
)?; )?;
let result = stmt.query_map([scope.unwrap_or("%")], |row| { let result = stmt.query_map([scope.unwrap_or("%")], |row| {
Ok(Table { Ok(Table {
id: row.get(0)?, id: row.get(0)?,
profile_identity_gemini_id: row.get(1)?, profile_identity_id: row.get(1)?,
scope: row.get(2)?, scope: row.get(2)?,
}) })
})?; })?;
@ -142,20 +135,20 @@ pub fn select_scope(tx: &Transaction, scope: Option<&str>) -> Result<Vec<Table>,
Ok(records) Ok(records)
} }
pub fn select_ref(tx: &Transaction, profile_identity_gemini_id: i64) -> Result<Vec<Table>, Error> { pub fn select_ref(tx: &Transaction, profile_identity_id: i64) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare( let mut stmt = tx.prepare(
"SELECT `id`, "SELECT `id`,
`profile_identity_gemini_id`, `profile_identity_id`,
`scope` `scope`
FROM `profile_identity_gemini_auth` FROM `profile_identity_auth`
WHERE `profile_identity_gemini_id` = ?", WHERE `profile_identity_id` = ?",
)?; )?;
let result = stmt.query_map([profile_identity_gemini_id], |row| { let result = stmt.query_map([profile_identity_id], |row| {
Ok(Table { Ok(Table {
id: row.get(0)?, id: row.get(0)?,
profile_identity_gemini_id: row.get(1)?, profile_identity_id: row.get(1)?,
scope: row.get(2)?, scope: row.get(2)?,
}) })
})?; })?;

View file

@ -29,9 +29,9 @@ impl Memory {
// Actions // Actions
/// Add new record with `scope` as key and `profile_identity_gemini_id` as value /// Add new record with `scope` as key and `profile_identity_id` as value
/// * validate record with same key does not exist yet /// * validate record with same key does not exist yet
pub fn add(&self, scope: String, profile_identity_gemini_id: i64) -> Result<(), Error> { pub fn add(&self, scope: String, profile_identity_id: i64) -> Result<(), Error> {
// Borrow shared index access // Borrow shared index access
let mut index = self.index.borrow_mut(); let mut index = self.index.borrow_mut();
@ -41,7 +41,7 @@ impl Memory {
} }
// Slot should be free, let check it twice // Slot should be free, let check it twice
match index.insert(scope, profile_identity_gemini_id) { match index.insert(scope, profile_identity_id) {
Some(_) => Err(Error::Unexpected), Some(_) => Err(Error::Unexpected),
None => Ok(()), None => Ok(()),
} }
@ -65,10 +65,10 @@ impl Memory {
let mut result = Vec::new(); let mut result = Vec::new();
// Get all records starts with `scope` // Get all records starts with `scope`
for (scope, &profile_identity_gemini_id) in self.index.borrow().iter() { for (scope, &profile_identity_id) in self.index.borrow().iter() {
if alias(request).starts_with(scope) { if request.starts_with(scope) {
result.push(Auth { result.push(Auth {
profile_identity_gemini_id, profile_identity_id,
scope: scope.clone(), scope: scope.clone(),
}) })
} }
@ -81,12 +81,3 @@ impl Memory {
result.first().cloned() result.first().cloned()
} }
} }
// Tools
// @TODO optional
fn alias(request: &str) -> String {
request
.replace("gemini://", "titan://")
.replace("titan://", "gemini://")
}

View file

@ -1,5 +1,5 @@
#[derive(Clone)] #[derive(Clone)]
pub struct Auth { pub struct Auth {
pub profile_identity_gemini_id: i64, pub profile_identity_id: i64,
pub scope: String, pub scope: String,
} }

View file

@ -3,57 +3,37 @@ use std::{rc::Rc, sync::RwLock};
pub struct Table { pub struct Table {
pub id: i64, pub id: i64,
pub profile_id: i64, //pub profile_id: i64,
pub is_active: bool, pub pem: String,
} }
/// Storage for Gemini auth certificates
pub struct Database { pub struct Database {
pub connection: Rc<RwLock<Connection>>, connection: Rc<RwLock<Connection>>,
profile_id: Rc<i64>, // multi-profile relationship
} }
impl Database { impl Database {
// Constructors // Constructors
/// Create new `Self` /// Create new `Self`
pub fn build(connection: &Rc<RwLock<Connection>>) -> Self { pub fn build(connection: &Rc<RwLock<Connection>>, profile_id: &Rc<i64>) -> Self {
Self { Self {
connection: connection.clone(), connection: connection.clone(),
profile_id: profile_id.clone(),
} }
} }
// Getters // Actions
/// Get all records /// Create new record in database
pub fn records(&self) -> Result<Vec<Table>, Error> { pub fn add(&self, pem: &str) -> Result<i64, Error> {
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction()?;
select(&tx)
}
/// Get active identity record if exist
pub fn active(&self) -> Result<Option<Table>, Error> {
let records = self.records()?;
Ok(records.into_iter().find(|record| record.is_active))
}
// Setters
/// Create new record in `Self` database connected
pub fn add(&self, profile_id: &Rc<i64>, is_active: bool) -> Result<i64, Error> {
// Begin new transaction // Begin new transaction
let mut writable = self.connection.write().unwrap(); let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?; let tx = writable.transaction()?;
// New record has active status
if is_active {
// Deactivate other records as only one profile should be active
for record in select(&tx)? {
update(&tx, record.profile_id, record.id, false)?;
}
}
// Create new record // Create new record
insert(&tx, profile_id, is_active)?; insert(&tx, *self.profile_id, pem)?;
// Hold insert ID for result // Hold insert ID for result
let id = last_insert_id(&tx); let id = last_insert_id(&tx);
@ -64,6 +44,44 @@ impl Database {
Err(e) => Err(e), Err(e) => Err(e),
} }
} }
/// Delete record with given `id` from database
pub fn delete(&self, id: i64) -> Result<(), Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
delete(&tx, id)?;
// Done
match tx.commit() {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
/// Get single record match `id`
pub fn record(&self, id: i64) -> Result<Option<Table>, Error> {
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction()?;
let records = select(&tx, *self.profile_id)?; // @TODO single record query
for record in records {
if record.id == id {
return Ok(Some(record));
}
}
Ok(None)
}
/// Get all records match current `profile_id`
pub fn records(&self) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap(); // @TODO
let tx = readable.unchecked_transaction()?;
select(&tx, *self.profile_id)
}
} }
// Low-level DB API // Low-level DB API
@ -74,7 +92,7 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
( (
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_id` INTEGER NOT NULL, `profile_id` INTEGER NOT NULL,
`is_active` INTEGER NOT NULL, `pem` TEXT NOT NULL,
FOREIGN KEY (`profile_id`) REFERENCES `profile`(`id`) FOREIGN KEY (`profile_id`) REFERENCES `profile`(`id`)
)", )",
@ -82,34 +100,34 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
) )
} }
pub fn insert(tx: &Transaction, profile_id: &Rc<i64>, is_active: bool) -> Result<usize, Error> { pub fn insert(tx: &Transaction, profile_id: i64, pem: &str) -> Result<usize, Error> {
tx.execute( tx.execute(
"INSERT INTO `profile_identity` ( "INSERT INTO `profile_identity` (
`profile_id`, `profile_id`,
`is_active` `pem`
) VALUES (?, ?)", ) VALUES (?, ?)",
(profile_id, is_active), (profile_id, pem),
) )
} }
pub fn update(tx: &Transaction, id: i64, profile_id: i64, is_active: bool) -> Result<usize, Error> { pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> {
tx.execute( tx.execute("DELETE FROM `profile_identity` WHERE `id` = ?", [id])
"UPDATE `profile_identity`
SET `profile_id` = ?,
`is_active` = ?
WHERE
`id` = ?",
(profile_id, is_active, id),
)
} }
pub fn select(tx: &Transaction) -> Result<Vec<Table>, Error> { pub fn select(tx: &Transaction, profile_id: i64) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare("SELECT `id`, `profile_id`, `is_active` FROM `profile_identity`")?; let mut stmt = tx.prepare(
let result = stmt.query_map([], |row| { "SELECT `id`,
`profile_id`,
`pem`
FROM `profile_identity` WHERE `profile_id` = ?",
)?;
let result = stmt.query_map([profile_id], |row| {
Ok(Table { Ok(Table {
id: row.get(0)?, id: row.get(0)?,
profile_id: row.get(1)?, //profile_id: row.get(1)?,
is_active: row.get(2)?, pem: row.get(2)?,
}) })
})?; })?;

View file

@ -2,19 +2,23 @@ use std::fmt::{Display, Formatter, Result};
#[derive(Debug)] #[derive(Debug)]
pub enum Error { pub enum Error {
Auth(super::auth::Error),
Certificate(Box<dyn std::error::Error>),
Database(sqlite::Error), Database(sqlite::Error),
Gemini(super::gemini::Error), Memory(super::memory::Error),
} }
impl Display for Error { impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
match self { match self {
Self::Auth(e) => write!(f, "Could not create auth: {e}"),
Self::Certificate(e) => {
write!(f, "Could not create certificate: {e}")
}
Self::Database(e) => { Self::Database(e) => {
write!(f, "Database error: {e}") write!(f, "Database error: {e}")
} }
Self::Gemini(e) => { Self::Memory(e) => write!(f, "Memory error: {e}"),
write!(f, "Could not init Gemini identity: {e}")
}
} }
} }
} }

View file

@ -1,158 +0,0 @@
mod auth;
mod certificate;
mod database;
mod error;
mod identity;
mod memory;
use auth::Auth;
use database::Database;
pub use error::Error;
use identity::Identity;
use memory::Memory;
use gtk::glib::DateTime;
use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock};
/// Authorization wrapper for Gemini protocol
///
/// https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates
pub struct Gemini {
pub auth: Rc<Auth>,
pub database: Rc<Database>,
pub memory: Rc<Memory>,
}
impl Gemini {
// Constructors
/// Create new `Self`
pub fn build(
connection: &Rc<RwLock<Connection>>,
profile_identity_id: &Rc<i64>,
) -> Result<Self, Error> {
// Init components
let auth = match Auth::new(connection) {
Ok(auth) => Rc::new(auth),
Err(e) => return Err(Error::Auth(e)),
};
let database = Rc::new(Database::build(connection, profile_identity_id));
let memory = Rc::new(Memory::new());
// Init `Self`
let this = Self {
auth,
database,
memory,
};
// Build initial index
Self::index(&this)?;
Ok(this)
}
// Actions
/// Add new record to database, update memory index
/// * return new `profile_identity_gemini_id` on success
pub fn add(&self, pem: &str) -> Result<i64, Error> {
match self.database.add(pem) {
Ok(profile_identity_gemini_id) => {
self.index()?;
Ok(profile_identity_gemini_id)
}
Err(e) => Err(Error::Database(e)),
}
}
/// Delete record from database including children dependencies, update memory index
pub fn delete(&self, profile_identity_gemini_id: i64) -> Result<(), Error> {
match self.auth.remove_ref(profile_identity_gemini_id) {
Ok(_) => match self.database.delete(profile_identity_gemini_id) {
Ok(_) => {
self.index()?;
Ok(())
}
Err(e) => Err(Error::Database(e)),
},
Err(e) => Err(Error::Auth(e)),
}
}
/// Generate new certificate and insert record to DB, update memory index
/// * return new `profile_identity_gemini_id` on success
pub fn make(&self, time: Option<(DateTime, DateTime)>, name: &str) -> Result<i64, Error> {
// Generate new certificate
match certificate::generate(
match time {
Some(value) => value,
None => (
DateTime::now_local().unwrap(),
DateTime::from_local(9999, 12, 31, 23, 59, 59.9).unwrap(), // max @TODO
),
},
name,
) {
Ok(pem) => self.add(&pem),
Err(e) => Err(Error::Certificate(e)),
}
}
/// Create new `Memory` index from `Database` for `Self`
pub fn index(&self) -> Result<(), Error> {
// Clear previous records
if let Err(e) = self.memory.clear() {
return Err(Error::Memory(e));
}
// Build new index
match self.database.records() {
Ok(records) => {
for record in records {
if let Err(e) = self.memory.add(record.id, record.pem) {
return Err(Error::Memory(e));
}
}
}
Err(e) => return Err(Error::Database(e)),
};
Ok(())
}
/// Get `Identity` match `request`
/// * [Client certificates specification](https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates)
/// * this function work with memory cache (not database)
pub fn match_scope(&self, request: &str) -> Option<Identity> {
if let Some(auth) = self.auth.memory.match_scope(request) {
match self.memory.get(auth.profile_identity_gemini_id) {
Ok(pem) => {
return Some(Identity {
// scope: auth.scope,
pem,
});
}
Err(e) => todo!("{:?}", e.to_string()),
}
}
None
}
}
// Tools
pub fn migrate(tx: &Transaction) -> Result<(), String> {
// Migrate self components
if let Err(e) = database::init(tx) {
return Err(e.to_string());
}
// Delegate migration to childs
auth::migrate(tx)?;
// Success
Ok(())
}

View file

@ -1,146 +0,0 @@
use sqlite::{Connection, Error, Transaction};
use std::{rc::Rc, sync::RwLock};
pub struct Table {
pub id: i64,
//pub profile_identity_id: i64,
pub pem: String,
}
/// Storage for Gemini auth certificates
pub struct Database {
connection: Rc<RwLock<Connection>>,
profile_identity_id: Rc<i64>, // multi-profile relationship
}
impl Database {
// Constructors
/// Create new `Self`
pub fn build(connection: &Rc<RwLock<Connection>>, profile_identity_id: &Rc<i64>) -> Self {
Self {
connection: connection.clone(),
profile_identity_id: profile_identity_id.clone(),
}
}
// Actions
/// Create new record in database
pub fn add(&self, pem: &str) -> Result<i64, Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
insert(&tx, *self.profile_identity_id, pem)?;
// Hold insert ID for result
let id = last_insert_id(&tx);
// Done
match tx.commit() {
Ok(_) => Ok(id),
Err(e) => Err(e),
}
}
/// Delete record with given `id` from database
pub fn delete(&self, id: i64) -> Result<(), Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
delete(&tx, id)?;
// Done
match tx.commit() {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
/// Get single record match `id`
pub fn record(&self, id: i64) -> Result<Option<Table>, Error> {
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction()?;
let records = select(&tx, *self.profile_identity_id)?; // @TODO single record query
for record in records {
if record.id == id {
return Ok(Some(record));
}
}
Ok(None)
}
/// Get all records match current `profile_identity_id`
pub fn records(&self) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap(); // @TODO
let tx = readable.unchecked_transaction()?;
select(&tx, *self.profile_identity_id)
}
}
// Low-level DB API
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `profile_identity_gemini`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_identity_id` INTEGER NOT NULL,
`pem` TEXT NOT NULL,
FOREIGN KEY (`profile_identity_id`) REFERENCES `profile_identity`(`id`)
)",
[],
)
}
pub fn insert(tx: &Transaction, profile_identity_id: i64, pem: &str) -> Result<usize, Error> {
tx.execute(
"INSERT INTO `profile_identity_gemini` (
`profile_identity_id`,
`pem`
) VALUES (?, ?)",
(profile_identity_id, pem),
)
}
pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> {
tx.execute("DELETE FROM `profile_identity_gemini` WHERE `id` = ?", [id])
}
pub fn select(tx: &Transaction, profile_identity_id: i64) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare(
"SELECT `id`,
`profile_identity_id`,
`pem`
FROM `profile_identity_gemini` WHERE `profile_identity_id` = ?",
)?;
let result = stmt.query_map([profile_identity_id], |row| {
Ok(Table {
id: row.get(0)?,
//profile_identity_id: row.get(1)?,
pem: row.get(2)?,
})
})?;
let mut records = Vec::new();
for record in result {
let table = record?;
records.push(table);
}
Ok(records)
}
pub fn last_insert_id(tx: &Transaction) -> i64 {
tx.last_insert_rowid()
}

View file

@ -1,24 +0,0 @@
use std::fmt::{Display, Formatter, Result};
#[derive(Debug)]
pub enum Error {
Auth(super::auth::Error),
Certificate(Box<dyn std::error::Error>),
Database(sqlite::Error),
Memory(super::memory::Error),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
match self {
Self::Auth(e) => write!(f, "Could not create auth: {e}"),
Self::Certificate(e) => {
write!(f, "Could not create certificate: {e}")
}
Self::Database(e) => {
write!(f, "Database error: {e}")
}
Self::Memory(e) => write!(f, "Memory error: {e}"),
}
}
}

View file

@ -5,12 +5,12 @@ use gtk::gio::TlsCertificate;
/// Gemini identity holder for cached record in application-wide struct format. /// Gemini identity holder for cached record in application-wide struct format.
/// Implements also additional conversion methods. /// Implements also additional conversion methods.
pub struct Identity { pub struct Item {
pub pem: String, pub pem: String,
// pub scope: String, // pub scope: String,
} }
impl Identity { impl Item {
/// Convert `Self` to [TlsCertificate](https://docs.gtk.org/gio/class.TlsCertificate.html) /// Convert `Self` to [TlsCertificate](https://docs.gtk.org/gio/class.TlsCertificate.html)
pub fn to_tls_certificate(&self) -> Result<TlsCertificate, Error> { pub fn to_tls_certificate(&self) -> Result<TlsCertificate, Error> {
match TlsCertificate::from_pem(&self.pem) { match TlsCertificate::from_pem(&self.pem) {

View file

@ -28,17 +28,17 @@ impl Memory {
/// Add new record with `id` as key and `pem` as value /// Add new record with `id` as key and `pem` as value
/// * validate record with same key does not exist yet /// * validate record with same key does not exist yet
pub fn add(&self, profile_identity_gemini_id: i64, pem: String) -> Result<(), Error> { pub fn add(&self, profile_identity_id: i64, pem: String) -> Result<(), Error> {
// Borrow shared index access // Borrow shared index access
let mut index = self.index.borrow_mut(); let mut index = self.index.borrow_mut();
// Prevent existing key overwrite // Prevent existing key overwrite
if index.contains_key(&profile_identity_gemini_id) { if index.contains_key(&profile_identity_id) {
return Err(Error::Overwrite(profile_identity_gemini_id)); return Err(Error::Overwrite(profile_identity_id));
} }
// Slot should be free, let check it twice // Slot should be free, let check it twice
match index.insert(profile_identity_gemini_id, pem) { match index.insert(profile_identity_id, pem) {
Some(_) => Err(Error::Unexpected), Some(_) => Err(Error::Unexpected),
None => Ok(()), None => Ok(()),
} }