Skip to main content

tuwunel_service/threepid/
binding.rs

1//! Persistent email-to-user bindings.
2//!
3//! Forward rows retain binding metadata for each user, while reverse rows
4//! resolve one canonical email to its owner. Streamed listing and point lookup
5//! expose the two index directions to account and invitation flows.
6
7use futures::{Stream, StreamExt};
8use ruma::{
9	MilliSecondsSinceUnixEpoch, OwnedUserId, UserId,
10	thirdparty::{Medium, ThirdPartyIdentifier, ThirdPartyIdentifierInit},
11};
12use tuwunel_core::{Result, implement, result::NotFound, utils::stream::TryIgnore};
13use tuwunel_database::{Cbor, Deserialized, Ignore, Interfix};
14
15use super::{Binding, EmailKey, canonicalize_email};
16
17/// Persists a canonical email binding unless another account holds it.
18///
19/// Returns whether `user_id` now holds the address; an address bound to a
20/// different account is left with it. Calls are serialized per address, so of
21/// two concurrent calls for different accounts only the first binds it; direct
22/// `put_binding` and `del_binding` writers do not take that lock. Storage and
23/// decoding failures from the ownership lookup are propagated.
24#[implement(super::Service)]
25#[tracing::instrument(
26	level = "debug",
27	skip(self),
28	fields(
29		%user_id,
30	),
31)]
32pub async fn bind_unclaimed(
33	&self,
34	user_id: &UserId,
35	email_canon: &str,
36	medium: Medium,
37	bound_at: MilliSecondsSinceUnixEpoch,
38) -> Result<bool> {
39	let _binding = self
40		.binding_mutex
41		.lock(&EmailKey::from(email_canon))
42		.await;
43
44	if self.bound_elsewhere(user_id, email_canon).await? {
45		return Ok(false);
46	}
47
48	self.put_binding(user_id, email_canon, medium, bound_at, bound_at)
49		.await;
50
51	Ok(true)
52}
53
54/// Persists a canonical email binding in both index directions.
55///
56/// The forward row stores the medium and timestamps, while the reverse row
57/// stores the owning user. These are separate map writes, so callers must not
58/// treat the two rows as one atomic snapshot.
59#[implement(super::Service)]
60#[tracing::instrument(
61	level = "debug",
62	skip(self),
63	fields(
64		%user_id,
65	),
66)]
67pub async fn put_binding(
68	&self,
69	user_id: &UserId,
70	email_canon: &str,
71	medium: Medium,
72	validated_at: MilliSecondsSinceUnixEpoch,
73	added_at: MilliSecondsSinceUnixEpoch,
74) {
75	let binding = Binding { medium, validated_at, added_at };
76
77	self.db
78		.userid_email
79		.put((user_id, email_canon), Cbor(binding));
80
81	self.db.email_userid.insert(email_canon, user_id);
82}
83
84/// Streams all third-party identifiers bound to `user_id`.
85///
86/// Entries are decoded lazily from the user's forward-index prefix. Storage or
87/// decoding failures are skipped, and each yielded identifier owns its data.
88#[implement(super::Service)]
89#[tracing::instrument(
90	level = "debug",
91	skip(self),
92	fields(
93		%user_id,
94	),
95)]
96pub fn get_bindings<'a>(
97	&'a self,
98	user_id: &'a UserId,
99) -> impl Stream<Item = ThirdPartyIdentifier> + Send + 'a {
100	type KeyVal = ((Ignore, String), Cbor<Binding>);
101
102	self.db
103		.userid_email
104		.stream_prefix(&(user_id, Interfix))
105		.ignore_err()
106		.map(|((_, address), Cbor(binding)): KeyVal| {
107			ThirdPartyIdentifierInit {
108				address,
109				medium: binding.medium,
110				validated_at: binding.validated_at,
111				added_at: binding.added_at,
112			}
113			.into()
114		})
115}
116
117/// Removes a canonical email binding from both index directions.
118///
119/// The forward row is deleted even when absent. The reverse row is removed
120/// only when a successful lookup still names this user, so a read failure or a
121/// different owner leaves that row untouched.
122#[implement(super::Service)]
123#[tracing::instrument(
124	level = "debug",
125	skip(self),
126	fields(
127		%user_id,
128	),
129)]
130pub async fn del_binding(&self, user_id: &UserId, email_canon: &str) {
131	self.db.userid_email.del((user_id, email_canon));
132
133	if self
134		.user_id_for_email(email_canon)
135		.await
136		.ok()
137		.flatten()
138		.is_some_and(|bound| bound == user_id)
139	{
140		self.db.email_userid.remove(email_canon);
141	}
142}
143
144/// Whether a canonical email address is bound to an account other than this
145/// one.
146///
147/// No binding or a binding to `user_id` returns `false`. Storage and decoding
148/// failures from the reverse lookup are propagated.
149#[implement(super::Service)]
150#[tracing::instrument(
151	level = "debug",
152	skip(self),
153	fields(
154		%user_id,
155	),
156)]
157pub async fn bound_elsewhere(&self, user_id: &UserId, email_canon: &str) -> Result<bool> {
158	self.user_id_for_email(email_canon)
159		.await
160		.map(|bound| bound.is_some_and(|bound| bound != user_id))
161}
162
163/// Whether an email address, as given, is bound to `user_id`.
164///
165/// An address that does not canonicalize was never bound, so it answers
166/// `false`. Storage and decoding failures from the reverse lookup are
167/// propagated.
168#[implement(super::Service)]
169#[tracing::instrument(
170	level = "debug",
171	skip(self, address),
172	fields(
173		%user_id,
174	),
175)]
176pub async fn address_bound_to(&self, user_id: &UserId, address: &str) -> Result<bool> {
177	let Ok(email_canon) = canonicalize_email(address) else {
178		return Ok(false);
179	};
180
181	self.user_id_for_email(&email_canon)
182		.await
183		.map(|bound| bound.is_some_and(|bound| bound == user_id))
184}
185
186/// Returns the user bound to a canonical email address.
187///
188/// An absent reverse row returns `None`. Storage and user-ID decoding failures
189/// are propagated.
190#[implement(super::Service)]
191#[tracing::instrument(level = "debug", skip(self))]
192pub async fn user_id_for_email(&self, email_canon: &str) -> Result<Option<OwnedUserId>> {
193	self.db
194		.email_userid
195		.get(email_canon)
196		.await
197		.optional()?
198		.map(|handle| handle.deserialized())
199		.transpose()
200}
201
202/// Tests whether a canonical email address has a readable reverse row.
203///
204/// Any successful raw lookup returns `true` without decoding the stored user.
205/// Absence and all storage failures are both collapsed to `false`.
206#[implement(super::Service)]
207#[tracing::instrument(level = "debug", skip(self))]
208pub async fn address_in_use(&self, email_canon: &str) -> bool {
209	self.db
210		.email_userid
211		.get(email_canon)
212		.await
213		.is_ok()
214}