From 774307241163a959505f20725e486b2df6abaeb9 Mon Sep 17 00:00:00 2001 From: link2xt Date: Tue, 10 Sep 2024 22:29:55 +0000 Subject: [PATCH] refactor: remove `addr` from KeyPair --- deltachat-ffi/deltachat.h | 5 +--- deltachat-ffi/src/lib.rs | 5 +--- python/src/deltachat/account.py | 4 +-- python/src/deltachat/testplugin.py | 10 +++---- python/tests/test_3_offline.py | 2 +- src/imex.rs | 4 --- src/key.rs | 17 +++-------- src/pgp.rs | 4 --- src/test_utils.rs | 47 +++++++++++++----------------- 9 files changed, 33 insertions(+), 65 deletions(-) diff --git a/deltachat-ffi/deltachat.h b/deltachat-ffi/deltachat.h index c3e1608cb..e4f57662e 100644 --- a/deltachat-ffi/deltachat.h +++ b/deltachat-ffi/deltachat.h @@ -864,13 +864,10 @@ void dc_maybe_network (dc_context_t* context); * * @memberof dc_context_t * @param context The context as created by dc_context_new(). - * @param addr The e-mail address of the user. This must match the - * configured_addr setting of the context as well as the UID of the key. - * @param public_data Ignored, actual public key is extracted from secret_data. * @param secret_data ASCII armored secret key. * @return 1 on success, 0 on failure. */ -int dc_preconfigure_keypair (dc_context_t* context, const char *addr, const char *public_data, const char *secret_data); +int dc_preconfigure_keypair (dc_context_t* context, const char *secret_data); // handle chatlists diff --git a/deltachat-ffi/src/lib.rs b/deltachat-ffi/src/lib.rs index 29ac3a827..601718c07 100644 --- a/deltachat-ffi/src/lib.rs +++ b/deltachat-ffi/src/lib.rs @@ -835,8 +835,6 @@ pub unsafe extern "C" fn dc_maybe_network(context: *mut dc_context_t) { #[no_mangle] pub unsafe extern "C" fn dc_preconfigure_keypair( context: *mut dc_context_t, - addr: *const libc::c_char, - _public_data: *const libc::c_char, secret_data: *const libc::c_char, ) -> i32 { if context.is_null() { @@ -844,9 +842,8 @@ pub unsafe extern "C" fn dc_preconfigure_keypair( return 0; } let ctx = &*context; - let addr = to_string_lossy(addr); let secret_data = to_string_lossy(secret_data); - block_on(preconfigure_keypair(ctx, &addr, &secret_data)) + block_on(preconfigure_keypair(ctx, &secret_data)) .context("Failed to save keypair") .log_err(ctx) .is_ok() as libc::c_int diff --git a/python/src/deltachat/account.py b/python/src/deltachat/account.py index e50d354bf..aca7fb763 100644 --- a/python/src/deltachat/account.py +++ b/python/src/deltachat/account.py @@ -194,15 +194,13 @@ class Account: assert res != ffi.NULL, f"config value not found for: {name!r}" return from_dc_charpointer(res) - def _preconfigure_keypair(self, addr: str, secret: str) -> None: + def _preconfigure_keypair(self, secret: str) -> None: """See dc_preconfigure_keypair() in deltachat.h. In other words, you don't need this. """ res = lib.dc_preconfigure_keypair( self._dc_context, - as_dc_charpointer(addr), - ffi.NULL, as_dc_charpointer(secret), ) if res == 0: diff --git a/python/src/deltachat/testplugin.py b/python/src/deltachat/testplugin.py index 17be65fca..388e6325d 100644 --- a/python/src/deltachat/testplugin.py +++ b/python/src/deltachat/testplugin.py @@ -462,7 +462,7 @@ class ACFactory: def remove_preconfigured_keys(self) -> None: self._preconfigured_keys = [] - def _preconfigure_key(self, account, addr): + def _preconfigure_key(self, account): # Only set a preconfigured key if we haven't used it yet for another account. try: keyname = self._preconfigured_keys.pop(0) @@ -471,9 +471,9 @@ class ACFactory: else: fname_sec = self.data.read_path(f"key/{keyname}-secret.asc") if fname_sec: - account._preconfigure_keypair(addr, fname_sec) + account._preconfigure_keypair(fname_sec) return True - print(f"WARN: could not use preconfigured keys for {addr!r}") + print("WARN: could not use preconfigured keys") def get_pseudo_configured_account(self, passphrase: Optional[str] = None) -> Account: # do a pseudo-configured account @@ -492,7 +492,7 @@ class ACFactory: "configured": "1", }, ) - self._preconfigure_key(ac, addr) + self._preconfigure_key(ac) self._acsetup.init_logging(ac) return ac @@ -528,7 +528,7 @@ class ACFactory: configdict.setdefault("delete_server_after", 0) ac.update_config(configdict) self._acsetup._account2config[ac] = configdict - self._preconfigure_key(ac, configdict["addr"]) + self._preconfigure_key(ac) return ac def wait_configured(self, account) -> None: diff --git a/python/tests/test_3_offline.py b/python/tests/test_3_offline.py index 20a64e6e8..f6eb248c1 100644 --- a/python/tests/test_3_offline.py +++ b/python/tests/test_3_offline.py @@ -67,7 +67,7 @@ class TestOfflineAccountBasic: ac = acfactory.get_unconfigured_account() alice_secret = data.read_path("key/alice-secret.asc") assert alice_secret - ac._preconfigure_keypair("alice@example.org", alice_secret) + ac._preconfigure_keypair(alice_secret) def test_getinfo(self, acfactory): ac1 = acfactory.get_unconfigured_account() diff --git a/src/imex.rs b/src/imex.rs index 0b546187d..89273a7a5 100644 --- a/src/imex.rs +++ b/src/imex.rs @@ -5,7 +5,6 @@ use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; -use deltachat_contact_tools::EmailAddress; use futures::TryStreamExt; use futures_lite::FutureExt; @@ -178,10 +177,7 @@ async fn set_self_key(context: &Context, armored: &str, set_default: bool) -> Re info!(context, "No Autocrypt-Prefer-Encrypt header."); }; - let self_addr = context.get_primary_self_addr().await?; - let addr = EmailAddress::new(&self_addr)?; let keypair = pgp::KeyPair { - addr, public: public_key, secret: private_key, }; diff --git a/src/key.rs b/src/key.rs index 0bdc3d245..0182cd383 100644 --- a/src/key.rs +++ b/src/key.rs @@ -244,7 +244,7 @@ async fn generate_keypair(context: &Context) -> Result { let _guard = context.generating_key_mutex.lock().await; // Check if the key appeared while we were waiting on the lock. - match load_keypair(context, &addr).await? { + match load_keypair(context).await? { Some(key_pair) => Ok(key_pair), None => { let start = tools::Time::now(); @@ -266,10 +266,7 @@ async fn generate_keypair(context: &Context) -> Result { } } -pub(crate) async fn load_keypair( - context: &Context, - addr: &EmailAddress, -) -> Result> { +pub(crate) async fn load_keypair(context: &Context) -> Result> { let res = context .sql .query_row_optional( @@ -287,7 +284,6 @@ pub(crate) async fn load_keypair( Ok(if let Some((pub_bytes, sec_bytes)) = res { Some(KeyPair { - addr: addr.clone(), public: SignedPublicKey::from_slice(&pub_bytes)?, secret: SignedSecretKey::from_slice(&sec_bytes)?, }) @@ -371,15 +367,10 @@ pub(crate) async fn store_self_keypair( /// This API is used for testing purposes /// to avoid generating the key in tests. /// Use import/export APIs instead. -pub async fn preconfigure_keypair(context: &Context, addr: &str, secret_data: &str) -> Result<()> { - let addr = EmailAddress::new(addr)?; +pub async fn preconfigure_keypair(context: &Context, secret_data: &str) -> Result<()> { let secret = SignedSecretKey::from_asc(secret_data)?.0; let public = secret.split_public_key()?; - let keypair = KeyPair { - addr, - public, - secret, - }; + let keypair = KeyPair { public, secret }; store_self_keypair(context, &keypair, KeyPairUse::Default).await?; Ok(()) } diff --git a/src/pgp.rs b/src/pgp.rs index f1b032f27..7bbd9b78c 100644 --- a/src/pgp.rs +++ b/src/pgp.rs @@ -135,9 +135,6 @@ pub fn split_armored_data(buf: &[u8]) -> Result<(BlockType, BTreeMap Res .context("invalid public key generated")?; Ok(KeyPair { - addr, public: public_key, secret: secret_key, }) diff --git a/src/test_utils.rs b/src/test_utils.rs index c1836d706..05551558b 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -256,19 +256,28 @@ impl TestContextBuilder { /// Builds the [`TestContext`]. pub async fn build(self) -> TestContext { - let name = self.key_pair.as_ref().map(|key| key.addr.local.clone()); - - let test_context = TestContext::new_internal(name, self.log_sink).await; - if let Some(key_pair) = self.key_pair { - test_context - .configure_addr(&key_pair.addr.to_string()) - .await; + let userid = { + let public_key = &key_pair.public; + let id_bstr = public_key.details.users.first().unwrap().id.id(); + String::from_utf8(id_bstr.to_vec()).unwrap() + }; + let addr = mailparse::addrparse(&userid) + .unwrap() + .extract_single_info() + .unwrap() + .addr; + let name = EmailAddress::new(&addr).unwrap().local; + + let test_context = TestContext::new_internal(Some(name), self.log_sink).await; + test_context.configure_addr(&addr).await; key::store_self_keypair(&test_context, &key_pair, KeyPairUse::Default) .await .expect("Failed to save key"); + test_context + } else { + TestContext::new_internal(None, self.log_sink).await } - test_context } } @@ -979,55 +988,39 @@ impl SentMessage<'_> { /// /// The keypair was created using the crate::key::tests::gen_key test. pub fn alice_keypair() -> KeyPair { - let addr = EmailAddress::new("alice@example.org").unwrap(); - let public = key::SignedPublicKey::from_asc(include_str!("../test-data/key/alice-public.asc")) .unwrap() .0; let secret = key::SignedSecretKey::from_asc(include_str!("../test-data/key/alice-secret.asc")) .unwrap() .0; - KeyPair { - addr, - public, - secret, - } + KeyPair { public, secret } } /// Load a pre-generated keypair for bob@example.net from disk. /// /// Like [alice_keypair] but a different key and identity. pub fn bob_keypair() -> KeyPair { - let addr = EmailAddress::new("bob@example.net").unwrap(); let public = key::SignedPublicKey::from_asc(include_str!("../test-data/key/bob-public.asc")) .unwrap() .0; let secret = key::SignedSecretKey::from_asc(include_str!("../test-data/key/bob-secret.asc")) .unwrap() .0; - KeyPair { - addr, - public, - secret, - } + KeyPair { public, secret } } /// Load a pre-generated keypair for fiona@example.net from disk. /// /// Like [alice_keypair] but a different key and identity. pub fn fiona_keypair() -> KeyPair { - let addr = EmailAddress::new("fiona@example.net").unwrap(); let public = key::SignedPublicKey::from_asc(include_str!("../test-data/key/fiona-public.asc")) .unwrap() .0; let secret = key::SignedSecretKey::from_asc(include_str!("../test-data/key/fiona-secret.asc")) .unwrap() .0; - KeyPair { - addr, - public, - secret, - } + KeyPair { public, secret } } /// Utility to help wait for and retrieve events.