Skip to main content

tuwunel_service/migrations/
email_bindings.rs

1use std::sync::Arc;
2
3use futures::TryStreamExt;
4use ruma::{MilliSecondsSinceUnixEpoch, thirdparty::Medium};
5use tuwunel_core::{Err, Result, debug_warn, err, info, warn};
6use tuwunel_database::Map;
7
8use crate::{
9	Services,
10	integrity::email_bindings::{Bindable, Row, bindable, column, rows},
11};
12
13/// Adopts the email addresses a foreign database binds in a column of its own.
14///
15/// Some databases hold one address per localpart in their own column rather
16/// than in the third-party identifier store this server reads, so the binding
17/// is invisible here and the address looks unclaimed. Adopting it keeps the
18/// address answering for its owner, which is what an account authenticated by
19/// an identity provider carries instead of a password.
20pub(super) async fn migrate_email_bindings(services: &Services) -> Result {
21	let Some(localpart_email) = column(services)? else {
22		return Ok(());
23	};
24
25	adopt_email_bindings(services, &localpart_email).await
26}
27
28/// Adopts every binding an opened foreign column holds.
29///
30/// Addresses are taken one at a time because two foreign addresses can fold
31/// onto one canonical key, and a concurrent pass would clear both through the
32/// in-use check before either wrote the reverse row.
33pub(super) async fn adopt_email_bindings(
34	services: &Services,
35	localpart_email: &Arc<Map>,
36) -> Result {
37	let bound_at = MilliSecondsSinceUnixEpoch::now();
38	let cork = services.db.cork_and_sync();
39
40	let (adopted, skipped, unreadable) = rows(services, localpart_email)
41		.try_fold((0_usize, 0_usize, 0_usize), async |acc, row| {
42			Ok(tally_adoption(acc, adopt_one(services, bound_at, row).await))
43		})
44		.await?;
45
46	drop(cork);
47
48	match skipped {
49		| 0 if adopted > 0 => info!(%adopted, "Adopted email bindings from a foreign database"),
50		| 0 => (),
51		| _ => warn!(
52			%adopted,
53			%skipped,
54			"Adopted email bindings from a foreign database; some addresses were left behind"
55		),
56	}
57
58	// Leaving the marker unstamped is what makes a read failure recoverable: the
59	// pass is idempotent, so the next boot retries it whole.
60	unreadable
61		.eq(&0)
62		.then_some(())
63		.ok_or_else(|| err!(Database("{unreadable} email bindings could not be read")))
64}
65
66/// Binds one foreign row, reporting whether it produced a binding.
67///
68/// A `false` return is a row with nothing to bind: an unusable localpart or
69/// address, an account absent here, the server's own, or an address already
70/// held by a different account, which this store cannot represent twice. An
71/// error is a read that failed and must not be mistaken for any of them.
72async fn adopt_one(
73	services: &Services,
74	bound_at: MilliSecondsSinceUnixEpoch,
75	row: Row,
76) -> Result<bool> {
77	let (user_id, address) = match row {
78		| Row::Binding { user_id, address, .. } => (user_id, address),
79		| Row::UnusableLocalpart { localpart } => {
80			debug_warn!(%localpart, "skipping an unusable localpart");
81			return Ok(false);
82		},
83		| Row::Unparsable { key } => {
84			let key = key.escape_ascii();
85
86			return Err!(Database("email binding {key} is not text"));
87		},
88	};
89
90	let email_canon = match bindable(services, &user_id, &address).await? {
91		| Bindable::NoAccount => return Ok(false),
92		| Bindable::Canonical(email_canon) => email_canon,
93		| Bindable::UnusableAddress => {
94			debug_warn!(localpart = %user_id.localpart(), "skipping an unusable address");
95			return Ok(false);
96		},
97	};
98
99	services
100		.threepid
101		.bind_unclaimed(&user_id, &email_canon, Medium::Email, bound_at)
102		.await
103}
104
105fn tally_adoption(
106	(adopted, skipped, unreadable): (usize, usize, usize),
107	result: Result<bool>,
108) -> (usize, usize, usize) {
109	match result {
110		| Ok(true) => (adopted.saturating_add(1), skipped, unreadable),
111		| Ok(false) => (adopted, skipped.saturating_add(1), unreadable),
112		| Err(e) => {
113			warn!(error = %e, "an email binding could not be read");
114
115			(adopted, skipped, unreadable.saturating_add(1))
116		},
117	}
118}