move things to use default handler mechanism

This commit is contained in:
Ryan Heywood 2025-01-04 01:04:52 -05:00
parent f8db8702ce
commit c46f9e48b7
Signed by: ryan
GPG Key ID: 8E401478A3FBEF72
11 changed files with 76 additions and 84 deletions

View File

@ -11,7 +11,7 @@ pub struct BincodeLayer<'a, Request> {
phantom_request: PhantomData<&'a Request>,
}
impl<'a, Request> BincodeLayer<'a, Request> {
impl<Request> BincodeLayer<'_, Request> {
/// Create a new [`BincodeLayer`].
pub fn new() -> Self {
Self {
@ -21,7 +21,7 @@ impl<'a, Request> BincodeLayer<'a, Request> {
}
}
impl<'a, Request> Default for BincodeLayer<'a, Request> {
impl<Request> Default for BincodeLayer<'_, Request> {
fn default() -> Self {
Self::new()
}

View File

@ -7,7 +7,7 @@ use std::{
process::ExitCode,
};
use keyfork_prompt::{DefaultTerminal, default_terminal};
use keyfork_prompt::default_handler;
use keyfork_shard::{openpgp::OpenPGP, Format};
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
@ -32,8 +32,8 @@ fn run() -> Result<()> {
_ => panic!("Usage: {program_name} <shard> [key_discovery]"),
};
let openpgp = OpenPGP::<DefaultTerminal>::new();
let prompt_handler = default_terminal()?;
let openpgp = OpenPGP;
let prompt_handler = default_handler()?;
let bytes = openpgp.decrypt_all_shards_to_secret(key_discovery.as_deref(), messages_file, prompt_handler)?;
print!("{}", smex::encode(bytes));

View File

@ -7,7 +7,7 @@ use std::{
process::ExitCode,
};
use keyfork_prompt::{DefaultTerminal, default_terminal};
use keyfork_prompt::default_handler;
use keyfork_shard::{Format, openpgp::OpenPGP};
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
@ -32,8 +32,8 @@ fn run() -> Result<()> {
_ => panic!("Usage: {program_name} <shard> [key_discovery]"),
};
let openpgp = OpenPGP::<DefaultTerminal>::new();
let prompt_handler = default_terminal()?;
let openpgp = OpenPGP;
let prompt_handler = default_handler()?;
openpgp.decrypt_one_shard_for_transport(key_discovery.as_deref(), messages_file, prompt_handler)?;

View File

@ -2,7 +2,6 @@
use std::{env, path::PathBuf, process::ExitCode, str::FromStr};
use keyfork_prompt::terminal::DefaultTerminal;
use keyfork_shard::{Format, openpgp::OpenPGP};
#[derive(Clone, Debug)]
@ -51,7 +50,7 @@ fn run() -> Result<()> {
smex::decode(line?)?
};
let openpgp = OpenPGP::<DefaultTerminal>::new();
let openpgp = OpenPGP;
openpgp.shard_and_encrypt(threshold, max, &input, key_discovery.as_path(), std::io::stdout())?;
Ok(())

View File

@ -3,7 +3,8 @@
use std::{
io::{stdin, stdout, Read, Write},
sync::{Arc, Mutex},
sync::Mutex,
rc::Rc,
};
use aes_gcm::{
@ -136,7 +137,7 @@ pub trait Format {
&self,
private_keys: Option<Self::PrivateKeyData>,
encrypted_messages: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>,
prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> Result<(Vec<Share>, u8), Self::Error>;
/// Decrypt a single share and associated metadata from a reaable input. For the current
@ -150,7 +151,7 @@ pub trait Format {
&self,
private_keys: Option<Self::PrivateKeyData>,
encrypted_data: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>,
prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> Result<(Share, u8), Self::Error>;
/// Decrypt multiple shares and combine them to recreate a secret.
@ -162,7 +163,7 @@ pub trait Format {
&self,
private_key_discovery: Option<impl KeyDiscovery<Self>>,
reader: impl Read + Send + Sync,
prompt: impl PromptHandler,
prompt: Box<dyn PromptHandler>,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let private_keys = private_key_discovery
.map(|p| p.discover_private_keys())
@ -171,7 +172,7 @@ pub trait Format {
let (shares, threshold) = self.decrypt_all_shards(
private_keys,
&encrypted_messages,
Arc::new(Mutex::new(prompt)),
Rc::new(Mutex::new(prompt)),
)?;
let secret = Sharks(threshold)
@ -192,9 +193,9 @@ pub trait Format {
&self,
private_key_discovery: Option<impl KeyDiscovery<Self>>,
reader: impl Read + Send + Sync,
prompt: impl PromptHandler,
prompt: Box<dyn PromptHandler>,
) -> Result<(), Box<dyn std::error::Error>> {
let prompt = Arc::new(Mutex::new(prompt));
let prompt = Rc::new(Mutex::new(prompt));
// parse input
let private_keys = private_key_discovery
@ -236,7 +237,7 @@ pub trait Format {
};
let mut prompt = prompt.lock().expect(bug!(POISONED_MUTEX));
prompt_validated_wordlist::<English, _>(
&mut *prompt,
&mut **prompt,
QRCODE_COULDNT_READ,
3,
&*validator.to_fn(),

View File

@ -5,10 +5,10 @@
use std::{
collections::HashMap,
io::{Read, Write},
marker::PhantomData,
path::Path,
str::FromStr,
sync::{Arc, Mutex},
sync::Mutex,
rc::Rc,
};
use keyfork_bug::bug;
@ -186,18 +186,9 @@ impl EncryptedMessage {
}
/// Encoding and decoding shards using OpenPGP.
pub struct OpenPGP<P: PromptHandler> {
p: PhantomData<P>,
}
pub struct OpenPGP;
impl<P: PromptHandler> OpenPGP<P> {
#[allow(clippy::new_without_default, missing_docs)]
pub fn new() -> Self {
Self { p: PhantomData }
}
}
impl<P: PromptHandler> OpenPGP<P> {
impl OpenPGP {
/// Read all OpenPGP certificates in a path and return a [`Vec`] of them.
///
/// Certificates are read from a file, or from files one level deep in a directory.
@ -256,7 +247,7 @@ impl<P: PromptHandler> OpenPGP<P> {
const METADATA_MESSAGE_MISSING: &str = "Metadata message was not found in parsed packets";
impl<P: PromptHandler> Format for OpenPGP<P> {
impl Format for OpenPGP {
type Error = Error;
type PublicKey = Cert;
type PrivateKeyData = Vec<Cert>;
@ -453,7 +444,7 @@ impl<P: PromptHandler> Format for OpenPGP<P> {
&self,
private_keys: Option<Self::PrivateKeyData>,
encrypted_data: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>,
prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> std::result::Result<(Vec<Share>, u8), Self::Error> {
// Be as liberal as possible when decrypting.
// We don't want to invalidate someone's keys just because the old sig expired.
@ -514,7 +505,7 @@ impl<P: PromptHandler> Format for OpenPGP<P> {
&self,
private_keys: Option<Self::PrivateKeyData>,
encrypted_data: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>,
prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> std::result::Result<(Share, u8), Self::Error> {
let policy = NullPolicy::new();
@ -560,22 +551,22 @@ impl<P: PromptHandler> Format for OpenPGP<P> {
}
}
impl<P: PromptHandler> KeyDiscovery<OpenPGP<P>> for &Path {
fn discover_public_keys(&self) -> Result<Vec<<OpenPGP<P> as Format>::PublicKey>> {
OpenPGP::<P>::discover_certs(self)
impl KeyDiscovery<OpenPGP> for &Path {
fn discover_public_keys(&self) -> Result<Vec<<OpenPGP as Format>::PublicKey>> {
OpenPGP::discover_certs(self)
}
fn discover_private_keys(&self) -> Result<<OpenPGP<P> as Format>::PrivateKeyData> {
OpenPGP::<P>::discover_certs(self)
fn discover_private_keys(&self) -> Result<<OpenPGP as Format>::PrivateKeyData> {
OpenPGP::discover_certs(self)
}
}
impl<P: PromptHandler> KeyDiscovery<OpenPGP<P>> for &[Cert] {
fn discover_public_keys(&self) -> Result<Vec<<OpenPGP<P> as Format>::PublicKey>> {
impl KeyDiscovery<OpenPGP> for &[Cert] {
fn discover_public_keys(&self) -> Result<Vec<<OpenPGP as Format>::PublicKey>> {
Ok(self.to_vec())
}
fn discover_private_keys(&self) -> Result<<OpenPGP<P> as Format>::PrivateKeyData> {
fn discover_private_keys(&self) -> Result<<OpenPGP as Format>::PrivateKeyData> {
Ok(self.to_vec())
}
}
@ -637,12 +628,12 @@ fn decode_metadata_v1(buf: &[u8]) -> Result<(u8, Cert, Vec<Cert>)> {
// NOTE: When using single-decryptor mechanism, use this method with `threshold = 1` to return a
// single message.
fn decrypt_with_manager<P: PromptHandler>(
fn decrypt_with_manager(
threshold: u8,
messages: &mut HashMap<KeyID, EncryptedMessage>,
certs: &[Cert],
policy: &dyn Policy,
manager: &mut SmartcardManager<P>,
manager: &mut SmartcardManager,
) -> Result<HashMap<KeyID, Vec<u8>>> {
let mut decrypted_messages = HashMap::new();
@ -687,11 +678,11 @@ fn decrypt_with_manager<P: PromptHandler>(
// NOTE: When using single-decryptor mechanism, only a single key should be provided in Keyring to
// decrypt messages with.
fn decrypt_with_keyring<P: PromptHandler>(
fn decrypt_with_keyring(
messages: &mut HashMap<KeyID, EncryptedMessage>,
certs: &[Cert],
policy: &NullPolicy,
keyring: &mut Keyring<P>,
keyring: &mut Keyring,
) -> Result<HashMap<KeyID, Vec<u8>>, Error> {
let mut decrypted_messages = HashMap::new();
@ -721,11 +712,11 @@ fn decrypt_with_keyring<P: PromptHandler>(
Ok(decrypted_messages)
}
fn decrypt_metadata<P: PromptHandler>(
fn decrypt_metadata(
message: &EncryptedMessage,
policy: &NullPolicy,
keyring: &mut Keyring<P>,
manager: &mut SmartcardManager<P>,
keyring: &mut Keyring,
manager: &mut SmartcardManager,
) -> Result<Vec<u8>> {
Ok(if keyring.is_empty() {
manager.load_any_card()?;

View File

@ -1,6 +1,6 @@
#![allow(clippy::expect_fun_call)]
use std::sync::{Arc, Mutex};
use std::{rc::Rc, sync::Mutex};
use keyfork_bug::{bug, POISONED_MUTEX};
use keyfork_prompt::{Error as PromptError, PromptHandler};
@ -27,14 +27,14 @@ pub enum Error {
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub struct Keyring<P: PromptHandler> {
pub struct Keyring {
full_certs: Vec<Cert>,
root: Option<Cert>,
pm: Arc<Mutex<P>>,
pm: Rc<Mutex<Box<dyn PromptHandler>>>,
}
impl<P: PromptHandler> Keyring<P> {
pub fn new(certs: impl AsRef<[Cert]>, p: Arc<Mutex<P>>) -> Result<Self> {
impl Keyring {
pub fn new(certs: impl AsRef<[Cert]>, p: Rc<Mutex<Box<dyn PromptHandler>>>) -> Result<Self> {
Ok(Self {
full_certs: certs.as_ref().to_vec(),
root: Default::default(),
@ -62,7 +62,7 @@ impl<P: PromptHandler> Keyring<P> {
}
}
impl<P: PromptHandler> VerificationHelper for &mut Keyring<P> {
impl VerificationHelper for &mut Keyring {
fn get_certs(&mut self, ids: &[KeyHandle]) -> openpgp::Result<Vec<Cert>> {
Ok(ids
.iter()
@ -108,7 +108,7 @@ impl<P: PromptHandler> VerificationHelper for &mut Keyring<P> {
}
}
impl<P: PromptHandler> DecryptionHelper for &mut Keyring<P> {
impl DecryptionHelper for &mut Keyring {
fn decrypt<D>(
&mut self,
pkesks: &[PKESK],

View File

@ -2,7 +2,8 @@
use std::{
collections::{HashMap, HashSet},
sync::{Arc, Mutex},
rc::Rc,
sync::Mutex,
};
use keyfork_bug::{bug, POISONED_MUTEX};
@ -72,15 +73,15 @@ fn format_name(input: impl AsRef<str>) -> String {
}
#[allow(clippy::module_name_repetitions)]
pub struct SmartcardManager<P: PromptHandler> {
pub struct SmartcardManager {
current_card: Option<Card<Open>>,
root: Option<Cert>,
pm: Arc<Mutex<P>>,
pm: Rc<Mutex<Box<dyn PromptHandler>>>,
pin_cache: HashMap<Fingerprint, String>,
}
impl<P: PromptHandler> SmartcardManager<P> {
pub fn new(p: Arc<Mutex<P>>) -> Result<Self> {
impl SmartcardManager {
pub fn new(p: Rc<Mutex<Box<dyn PromptHandler>>>) -> Result<Self> {
Ok(Self {
current_card: None,
root: None,
@ -174,7 +175,7 @@ impl<P: PromptHandler> SmartcardManager<P> {
}
}
impl<P: PromptHandler> VerificationHelper for &mut SmartcardManager<P> {
impl VerificationHelper for &mut SmartcardManager {
fn get_certs(&mut self, ids: &[openpgp::KeyHandle]) -> openpgp::Result<Vec<Cert>> {
#[allow(clippy::flat_map_option)]
Ok(ids
@ -218,7 +219,7 @@ impl<P: PromptHandler> VerificationHelper for &mut SmartcardManager<P> {
}
}
impl<P: PromptHandler> DecryptionHelper for &mut SmartcardManager<P> {
impl DecryptionHelper for &mut SmartcardManager {
fn decrypt<D>(
&mut self,
pkesks: &[PKESK],
@ -277,7 +278,7 @@ impl<P: PromptHandler> DecryptionHelper for &mut SmartcardManager<P> {
format!("Unlock card {card_id} ({cardholder_name})\n{rpea}: {attempts}\n\nPIN: ")
};
let mut prompt = self.pm.lock().expect(bug!(POISONED_MUTEX));
let temp_pin = prompt_validated_passphrase(&mut *prompt, &message, 3, &pin_validator)?;
let temp_pin = prompt_validated_passphrase(&mut **prompt, &message, 3, &pin_validator)?;
let verification_status = transaction.verify_user_pin(temp_pin.as_str().trim());
match verification_status {
#[allow(clippy::ignored_unit_patterns)]

View File

@ -4,12 +4,11 @@ use std::path::PathBuf;
use keyfork_mnemonic::{English, Mnemonic};
use keyfork_prompt::{
default_terminal, prompt_validated_wordlist,
default_handler, prompt_validated_wordlist,
validators::{
mnemonic::{MnemonicChoiceValidator, WordLength},
Validator,
},
DefaultTerminal,
};
use keyfork_shard::{remote_decrypt, Format};
@ -42,8 +41,8 @@ impl RecoverSubcommands {
} => {
let content = std::fs::read_to_string(shard_file)?;
if content.contains("BEGIN PGP MESSAGE") {
let openpgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new();
let prompt_handler = default_terminal()?;
let openpgp = keyfork_shard::openpgp::OpenPGP;
let prompt_handler = default_handler()?;
// TODO: remove .clone() by making handle() consume self
let seed = openpgp.decrypt_all_shards_to_secret(
key_discovery.as_deref(),
@ -61,12 +60,12 @@ impl RecoverSubcommands {
Ok(seed)
}
RecoverSubcommands::Mnemonic {} => {
let mut term = default_terminal()?;
let mut prompt_handler = default_handler()?;
let validator = MnemonicChoiceValidator {
word_lengths: [WordLength::Count(12), WordLength::Count(24)],
};
let mnemonic = prompt_validated_wordlist::<English, _>(
&mut term,
&mut *prompt_handler,
"Mnemonic: ",
3,
&*validator.to_fn(),

View File

@ -1,6 +1,6 @@
use super::Keyfork;
use clap::{builder::PossibleValue, Parser, Subcommand, ValueEnum};
use keyfork_prompt::{default_terminal, DefaultTerminal};
use keyfork_prompt::default_handler;
use keyfork_shard::Format as _;
use std::{
io::{stdin, stdout, Read, Write},
@ -64,7 +64,7 @@ impl ShardExec for OpenPGP {
secret: &[u8],
output: &mut (impl Write + Send + Sync),
) -> Result<(), Box<dyn std::error::Error>> {
let opgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new();
let opgp = keyfork_shard::openpgp::OpenPGP;
opgp.shard_and_encrypt(threshold, max, secret, key_discovery, output)
}
@ -74,8 +74,8 @@ impl ShardExec for OpenPGP {
input: impl Read + Send + Sync,
output: &mut impl Write,
) -> Result<(), Box<dyn std::error::Error>> {
let openpgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new();
let prompt = default_terminal()?;
let openpgp = keyfork_shard::openpgp::OpenPGP;
let prompt = default_handler()?;
let bytes = openpgp.decrypt_all_shards_to_secret(key_discovery, input, prompt)?;
write!(output, "{}", smex::encode(bytes))?;
@ -87,8 +87,8 @@ impl ShardExec for OpenPGP {
key_discovery: Option<&Path>,
input: impl Read + Send + Sync,
) -> Result<(), Box<dyn std::error::Error>> {
let openpgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new();
let prompt = default_terminal()?;
let openpgp = keyfork_shard::openpgp::OpenPGP;
let prompt = default_handler()?;
openpgp.decrypt_one_shard_for_transport(key_discovery, input, prompt)?;
Ok(())
}

View File

@ -20,9 +20,10 @@ use keyfork_derive_path_data::paths;
use keyfork_derive_util::DerivationIndex;
use keyfork_mnemonic::Mnemonic;
use keyfork_prompt::{
default_terminal, prompt_validated_passphrase,
default_handler,
prompt_validated_passphrase,
validators::{SecurePinValidator, Validator},
DefaultTerminal, Message, PromptHandler,
Message,
};
use keyfork_shard::{openpgp::OpenPGP, Format};
@ -174,7 +175,7 @@ impl WizardSubcommands {
impl GenerateShardSecret {
fn handle(&self) -> Result<()> {
let seed = keyfork_entropy::generate_entropy_of_const_size::<{ 256 / 8 }>()?;
let mut pm = default_terminal()?;
let mut pm = default_handler()?;
let mut certs = vec![];
let mut seen_cards: HashSet<String> = HashSet::new();
let stdout = std::io::stdout();
@ -214,13 +215,13 @@ impl GenerateShardSecret {
))?;
};
let user_pin = prompt_validated_passphrase(
&mut pm,
&mut *pm,
"Please enter the new smartcard User PIN: ",
3,
&user_pin_validator,
)?;
let admin_pin = prompt_validated_passphrase(
&mut pm,
&mut *pm,
"Please enter the new smartcard Admin PIN: ",
3,
&admin_pin_validator,
@ -236,7 +237,7 @@ impl GenerateShardSecret {
certs.push(cert);
}
let opgp = OpenPGP::<DefaultTerminal>::new();
let opgp = OpenPGP;
if let Some(output_file) = self.output.as_ref() {
let output = File::create(output_file)?;
@ -284,8 +285,8 @@ impl BottomsUp {
cert.serialize(&mut w)?;
w.finalize()?;
let opgp = OpenPGP::<DefaultTerminal>::new();
let certs = OpenPGP::<DefaultTerminal>::discover_certs(&self.key_discovery)?;
let opgp = OpenPGP;
let certs = OpenPGP::discover_certs(&self.key_discovery)?;
let shardfile = File::create(&self.output_shardfile)?;
opgp.shard_and_encrypt(