Skip to main content

tuwunel_service/threepid/
mod.rs

1//! Email third-party identifier bindings and verification sessions.
2//!
3//! The service stores bidirectional email bindings, durable pending proofs,
4//! and UIAA ownership claims. Process-local token buckets separately limit
5//! verification requests by caller address and canonical email.
6
7mod binding;
8mod canonical;
9mod pending;
10mod ratelimit;
11
12use std::{
13	collections::HashMap,
14	net::IpAddr,
15	sync::{Arc, Mutex},
16	time::Instant,
17};
18
19use ruma::{MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, thirdparty::Medium};
20use serde::{Deserialize, Serialize};
21use tuwunel_core::{Result, smallstr::SmallString, utils::MutexMap};
22use tuwunel_database::{Database, Map};
23
24/// Public helpers and result types exposed by the threepid service.
25///
26/// Email canonicalization produces storage keys, while pending outcomes tell
27/// callers whether a verification message must be sent.
28/// Both APIs preserve the service's canonical addressing rules.
29pub use self::{canonical::canonicalize_email, pending::PendingOutcome};
30
31/// Token-bucket table keyed on a throttle axis: last-refill instant and
32/// remaining tokens per key.
33type Ratelimiter<K> = Mutex<HashMap<K, (Instant, f64)>>;
34
35/// Stack-string key for the per-address throttle bucket; the modal email
36/// canonical address fits inline.
37type EmailKey = SmallString<[u8; 48]>;
38
39/// Manages email threepid bindings, verification sessions, and request limits.
40///
41/// Persistent maps provide lookups from user to email and email to user.
42/// In-memory token buckets limit `requestToken` calls by caller IP and
43/// canonical address.
44pub struct Service {
45	db: Data,
46	pending_mutex: MutexMap<String, ()>,
47	claim_mutex: MutexMap<UiaaKey, ()>,
48
49	/// One entry per address in a `bind_unclaimed` call; MAS provisioning, the
50	/// admin API and `del_binding` write bindings without it.
51	binding_mutex: MutexMap<EmailKey, ()>,
52
53	ip_ratelimiter: Ratelimiter<IpAddr>,
54	address_ratelimiter: Ratelimiter<EmailKey>,
55}
56
57struct Data {
58	database: Arc<Database>,
59	userid_email: Arc<Map>,
60	email_userid: Arc<Map>,
61	threepidsid_pending: Arc<Map>,
62	userdevicesessionid_threepid: Arc<Map>,
63}
64
65/// Stores a UIAA session identifier inline in the common case.
66///
67/// The 32-byte budget matches identifiers minted by the UIAA service.
68/// Longer identifiers spill to the backing allocation without changing their
69/// value semantics.
70pub type UiaaSessionId = SmallString<[u8; 32]>;
71
72/// Identifies the exact UIAA session that owns a validated threepid.
73///
74/// Owned components let the durable claim key outlive an individual request.
75/// The tuple scopes a claim by user, device, and UIAA session identifier.
76pub type UiaaKey = (OwnedUserId, OwnedDeviceId, UiaaSessionId);
77
78/// CBOR value of a `userid_email` row: the per-binding metadata, with the
79/// address carried in the composite key.
80#[derive(Clone, Debug, Deserialize, Serialize)]
81struct Binding {
82	medium: Medium,
83	validated_at: MilliSecondsSinceUnixEpoch,
84	added_at: MilliSecondsSinceUnixEpoch,
85}
86
87/// Validated third-party identifier consumed from a pending proof.
88///
89/// Redemption returns the original medium and address stored with the
90/// verification session. Owning both values lets the result outlive the
91/// pending-row read.
92#[derive(Clone, Debug)]
93pub struct Association {
94	/// Third-party identifier medium that was verified.
95	pub medium: Medium,
96
97	/// Address exactly as stored by the verification session.
98	pub address: String,
99}
100
101impl crate::Service for Service {
102	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
103		Ok(Arc::new(Self {
104			db: Data {
105				database: args.db.clone(),
106				userid_email: args.db["userid_email"].clone(),
107				email_userid: args.db["email_userid"].clone(),
108				threepidsid_pending: args.db["threepidsid_pending"].clone(),
109				userdevicesessionid_threepid: args.db["userdevicesessionid_threepid"].clone(),
110			},
111			pending_mutex: MutexMap::new(),
112			claim_mutex: MutexMap::new(),
113			binding_mutex: MutexMap::new(),
114			ip_ratelimiter: Mutex::new(HashMap::new()),
115			address_ratelimiter: Mutex::new(HashMap::new()),
116		}))
117	}
118
119	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
120}