1use std::io::Cursor;
4
5use anyhow::Result;
6use mail_builder::mime::MimePart;
7use num_traits::FromPrimitive;
8
9use crate::aheader::{Aheader, EncryptPreference};
10use crate::config::Config;
11use crate::context::Context;
12use crate::key::{load_self_public_key, load_self_secret_key, SignedPublicKey};
13use crate::pgp;
14
15#[derive(Debug)]
16pub struct EncryptHelper {
17 pub prefer_encrypt: EncryptPreference,
18 pub addr: String,
19 pub public_key: SignedPublicKey,
20}
21
22impl EncryptHelper {
23 pub async fn new(context: &Context) -> Result<EncryptHelper> {
24 let prefer_encrypt =
25 EncryptPreference::from_i32(context.get_config_int(Config::E2eeEnabled).await?)
26 .unwrap_or_default();
27 let addr = context.get_primary_self_addr().await?;
28 let public_key = load_self_public_key(context).await?;
29
30 Ok(EncryptHelper {
31 prefer_encrypt,
32 addr,
33 public_key,
34 })
35 }
36
37 pub fn get_aheader(&self) -> Aheader {
38 let pk = self.public_key.clone();
39 let addr = self.addr.to_string();
40 Aheader::new(addr, pk, self.prefer_encrypt)
41 }
42
43 pub async fn encrypt(
45 self,
46 context: &Context,
47 keyring: Vec<SignedPublicKey>,
48 mail_to_encrypt: MimePart<'static>,
49 compress: bool,
50 ) -> Result<String> {
51 let sign_key = load_self_secret_key(context).await?;
52
53 let mut raw_message = Vec::new();
54 let cursor = Cursor::new(&mut raw_message);
55 mail_to_encrypt.clone().write_part(cursor).ok();
56
57 let ctext = pgp::pk_encrypt(raw_message, keyring, Some(sign_key), compress).await?;
58
59 Ok(ctext)
60 }
61
62 pub async fn sign(self, context: &Context, mail: &MimePart<'static>) -> Result<String> {
65 let sign_key = load_self_secret_key(context).await?;
66 let mut buffer = Vec::new();
67 mail.clone().write_part(&mut buffer)?;
68 let signature = pgp::pk_calc_signature(buffer, &sign_key)?;
69 Ok(signature)
70 }
71}
72
73pub async fn ensure_secret_key_exists(context: &Context) -> Result<()> {
81 load_self_public_key(context).await?;
82 Ok(())
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88 use crate::chat::send_text_msg;
89 use crate::config::Config;
90 use crate::message::Message;
91 use crate::receive_imf::receive_imf;
92 use crate::test_utils::{TestContext, TestContextManager};
93
94 mod ensure_secret_key_exists {
95 use super::*;
96
97 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
98 async fn test_prexisting() {
99 let t = TestContext::new_alice().await;
100 assert!(ensure_secret_key_exists(&t).await.is_ok());
101 }
102
103 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
104 async fn test_not_configured() {
105 let t = TestContext::new().await;
106 assert!(ensure_secret_key_exists(&t).await.is_err());
107 }
108 }
109
110 #[test]
111 fn test_mailmime_parse() {
112 let plain = b"Chat-Disposition-Notification-To: hello@world.de
113Chat-Group-ID: CovhGgau8M-
114Chat-Group-Name: Delta Chat Dev
115Subject: =?utf-8?Q?Chat=3A?= Delta Chat =?utf-8?Q?Dev=3A?= sidenote for
116 =?utf-8?Q?all=3A?= rust core master ...
117Content-Type: text/plain; charset=\"utf-8\"; protected-headers=\"v1\"
118Content-Transfer-Encoding: quoted-printable
119
120sidenote for all: things are trick atm recomm=
121end not to try to run with desktop or ios unless you are ready to hunt bugs
122
123-- =20
124Sent with my Delta Chat Messenger: https://delta.chat";
125 let mail = mailparse::parse_mail(plain).expect("failed to parse valid message");
126
127 assert_eq!(mail.headers.len(), 6);
128 assert!(
129 mail.get_body().unwrap().starts_with(
130 "sidenote for all: things are trick atm recommend not to try to run with desktop or ios unless you are ready to hunt bugs")
131 );
132 }
133
134 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
135 async fn test_chatmail_can_send_unencrypted() -> Result<()> {
136 let mut tcm = TestContextManager::new();
137 let bob = &tcm.bob().await;
138 bob.set_config_bool(Config::IsChatmail, true).await?;
139 let bob_chat_id = receive_imf(
140 bob,
141 b"From: alice@example.org\n\
142 To: bob@example.net\n\
143 Message-ID: <2222@example.org>\n\
144 Date: Sun, 22 Mar 3000 22:37:58 +0000\n\
145 \n\
146 Hello\n",
147 false,
148 )
149 .await?
150 .unwrap()
151 .chat_id;
152 bob_chat_id.accept(bob).await?;
153 send_text_msg(bob, bob_chat_id, "hi".to_string()).await?;
154 let sent_msg = bob.pop_sent_msg().await;
155 let msg = Message::load_from_db(bob, sent_msg.sender_msg_id).await?;
156 assert!(!msg.get_showpadlock());
157 Ok(())
158 }
159}