Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions deltachat-rpc-client/src/deltachat_rpc_client/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ def add_or_update_transport(self, params):
"""Add a new transport."""
yield self._rpc.add_or_update_transport.future(self.id, params)

@futuremethod
def add_transport_from_qr(self, qr: str):
"""Add a new transport using a QR code."""
yield self._rpc.add_transport_from_qr.future(self.id, qr)

@futuremethod
def list_transports(self):
"""Return the list of all email accounts that are used as a transport in the current profile."""
Expand Down
4 changes: 2 additions & 2 deletions deltachat-rpc-client/src/deltachat_rpc_client/pytestplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def new_configured_account(self):
"""Create a new configured account."""
addr, password = self.get_credentials()
account = self.get_unconfigured_account()
params = {"addr": addr, "password": password}
yield account.add_or_update_transport.future(params)
domain = os.getenv("CHATMAIL_DOMAIN")
yield account.add_transport_from_qr.future(f"dcaccount:{domain}")

assert account.is_configured()
return account
Expand Down
2 changes: 1 addition & 1 deletion deltachat-rpc-client/tests/test_something.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ def test_configured_imap_certificate_checks(acfactory):
alice = acfactory.new_configured_account()

# Certificate checks should be configured (not None)
assert "cert_automatic" in alice.get_info().used_account_settings
assert "cert_strict" in alice.get_info().used_account_settings

# "cert_old_automatic" is the value old Delta Chat core versions used
# to mean user entered "imap_certificate_checks=0" (Automatic)
Expand Down
51 changes: 38 additions & 13 deletions src/qr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ pub use dclogin_scheme::LoginOptions;
pub(crate) use dclogin_scheme::login_param_from_login_qr;
use deltachat_contact_tools::{ContactAddress, addr_normalize, may_be_valid_addr};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, percent_encode};
use rand::TryRngCore as _;
use rand::distr::{Alphanumeric, SampleString};
use serde::Deserialize;

use crate::config::Config;
Expand Down Expand Up @@ -543,21 +545,29 @@ async fn decode_ideltachat(context: &Context, prefix: &str, qr: &str) -> Result<
.with_context(|| format!("failed to decode {prefix} QR code"))
}

/// scheme: `DCACCOUNT:https://example.org/new_email?t=1w_7wDjgjelxeX884x96v3`
/// scheme: `DCACCOUNT:example.org`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would make sense to document this variant in the interface repo https://github.com/deltachat/interface/blob/main/uri-schemes.md

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/// or `DCACCOUNT:https://example.org/new`
/// or `DCACCOUNT:https://example.org/new_email?t=1w_7wDjgjelxeX884x96v3`
fn decode_account(qr: &str) -> Result<Qr> {
let payload = qr
.get(DCACCOUNT_SCHEME.len()..)
.context("Invalid DCACCOUNT payload")?;
let url = url::Url::parse(payload).context("Invalid account URL")?;
if url.scheme() == "http" || url.scheme() == "https" {
if payload.starts_with("https://") {
let url = url::Url::parse(payload).context("Invalid account URL")?;
if url.scheme() == "https" {
Ok(Qr::Account {
domain: url
.host_str()
.context("can't extract account setup domain")?
.to_string(),
})
} else {
bail!("Bad scheme for account URL: {:?}.", url.scheme());
}
} else {
Ok(Qr::Account {
domain: url
.host_str()
.context("can't extract account setup domain")?
.to_string(),
domain: payload.to_string(),
})
} else {
bail!("Bad scheme for account URL: {:?}.", url.scheme());
}
}

Expand Down Expand Up @@ -659,15 +669,30 @@ pub(crate) async fn login_param_from_account_qr(
context: &Context,
qr: &str,
) -> Result<EnteredLoginParam> {
let url_str = qr
let payload = qr
.get(DCACCOUNT_SCHEME.len()..)
.context("Invalid DCACCOUNT scheme")?;

if !url_str.starts_with(HTTPS_SCHEME) {
bail!("DCACCOUNT QR codes must use HTTPS scheme");
if !payload.starts_with(HTTPS_SCHEME) {
let rng = &mut rand::rngs::OsRng.unwrap_err();
let username = Alphanumeric.sample_string(rng, 9);
let addr = username + "@" + payload;
let password = Alphanumeric.sample_string(rng, 50);

let param = EnteredLoginParam {
addr,
imap: EnteredServerLoginParam {
password,
..Default::default()
},
smtp: Default::default(),
certificate_checks: EnteredCertificateChecks::Strict,
oauth2: false,
};
return Ok(param);
}

let (response_text, response_success) = post_empty(context, url_str).await?;
let (response_text, response_success) = post_empty(context, payload).await?;
if response_success {
let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text)
.with_context(|| {
Expand Down
53 changes: 12 additions & 41 deletions src/qr/qr_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,30 +643,20 @@ async fn test_decode_dclogin_advanced_options() -> Result<()> {
async fn test_decode_account() -> Result<()> {
let ctx = TestContext::new().await;

let qr = check_qr(
&ctx.ctx,
for text in [
"DCACCOUNT:example.org",
"dcaccount:example.org",
"DCACCOUNT:https://example.org/new_email?t=1w_7wDjgjelxeX884x96v3",
)
.await?;
assert_eq!(
qr,
Qr::Account {
domain: "example.org".to_string()
}
);

// Test it again with lowercased "dcaccount:" uri scheme
let qr = check_qr(
&ctx.ctx,
"dcaccount:https://example.org/new_email?t=1w_7wDjgjelxeX884x96v3",
)
.await?;
assert_eq!(
qr,
Qr::Account {
domain: "example.org".to_string()
}
);
] {
let qr = check_qr(&ctx.ctx, text).await?;
assert_eq!(
qr,
Qr::Account {
domain: "example.org".to_string()
}
);
}

Ok(())
}
Expand Down Expand Up @@ -734,25 +724,6 @@ async fn test_decode_tg_socks_proxy() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_decode_account_bad_scheme() {
let ctx = TestContext::new().await;
let res = check_qr(
&ctx.ctx,
"DCACCOUNT:ftp://example.org/new_email?t=1w_7wDjgjelxeX884x96v3",
)
.await;
assert!(res.is_err());

// Test it again with lowercased "dcaccount:" uri scheme
let res = check_qr(
&ctx.ctx,
"dcaccount:ftp://example.org/new_email?t=1w_7wDjgjelxeX884x96v3",
)
.await;
assert!(res.is_err());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_set_proxy_config_from_qr() -> Result<()> {
let t = TestContext::new().await;
Expand Down
10 changes: 4 additions & 6 deletions src/receive_imf/receive_imf_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use rand::Rng;
use std::time::Duration;

use tokio::fs;
Expand All @@ -20,6 +19,8 @@ use crate::test_utils::{
};
use crate::tools::{SystemTime, time};

use rand::distr::SampleString;

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_outgoing() -> Result<()> {
let context = TestContext::new_alice().await;
Expand Down Expand Up @@ -4339,11 +4340,8 @@ async fn test_download_later() -> Result<()> {
let bob_chat = bob.create_chat(&alice).await;

// Generate a random string so OpenPGP does not compress it.
let text: String = rand::rng()
.sample_iter(&rand::distr::Alphanumeric)
.take(MIN_DOWNLOAD_LIMIT as usize)
.map(char::from)
.collect();
let text =
rand::distr::Alphanumeric.sample_string(&mut rand::rng(), MIN_DOWNLOAD_LIMIT as usize);

let sent_msg = bob.send_text(bob_chat.id, &text).await;
let msg = alice.recv_msg(&sent_msg).await;
Expand Down
6 changes: 1 addition & 5 deletions src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ use mailparse::MailHeaderMap;
use mailparse::dateparse;
use mailparse::headers::Headers;
use num_traits::PrimInt;
use rand::Rng;
use tokio::{fs, io};
use url::Url;
use uuid::Uuid;
Expand Down Expand Up @@ -290,12 +289,9 @@ async fn maybe_warn_on_outdated(context: &Context, now: i64, approx_compile_time
/// (larger than AES-128 keys used for message encryption)
/// and divides both by 8 (byte size) and 6 (number of bits in a single Base64 character).
pub(crate) fn create_id() -> String {
// ThreadRng implements CryptoRng trait and is supposed to be cryptographically secure.
let mut rng = rand::rng();

// Generate 144 random bits.
let mut arr = [0u8; 18];
rng.fill(&mut arr[..]);
rand::fill(&mut arr[..]);

base64::engine::general_purpose::URL_SAFE.encode(arr)
}
Expand Down