Skip to main content

tuwunel_service/users/
device.rs

1use std::{
2	net::IpAddr,
3	time::{Duration, SystemTime},
4};
5
6use futures::{FutureExt, Stream, StreamExt, future::join};
7use ruma::{
8	DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
9	api::client::device::Device, events::AnyToDeviceEvent, serde::Raw,
10};
11use serde_json::json;
12use tuwunel_core::{
13	Err, Error, Result, async_noinline, at, debug_warn, implement,
14	smallstr::SmallString,
15	smallvec::SmallVec,
16	trace,
17	utils::{
18		BoolExt, MutexMapGuard, OptionExt, ReadyExt,
19		future::OptionFutureExt,
20		random_string,
21		stream::{BroadbandExt, IterStream, TryIgnore, automatic_width},
22		string::to_small_string,
23		time::{
24			deadline_has_passed, duration_since_epoch, timepoint_from_epoch, timepoint_from_now,
25			timepoint_has_passed,
26		},
27	},
28	warn,
29};
30use tuwunel_database::{Cbor, Deserialized, Ignore, Interfix, Json, Txn};
31
32use super::DeviceListChange;
33
34pub(super) type DeviceLock = MutexMapGuard<(OwnedUserId, OwnedDeviceId), ()>;
35type AccessToken = SmallString<[u8; TOKEN_LENGTH]>;
36type ExpiredTokens = SmallVec<[(SystemTime, AccessToken); 2]>;
37
38/// generated device ID length
39const DEVICE_ID_LENGTH: usize = 10;
40
41/// Longest device ID a client may choose, in bytes.
42///
43/// Synapse refuses one longer than 512 characters at login. Other servers
44/// receive the ID in every device list update.
45pub const MAX_DEVICE_ID_LENGTH: usize = 512;
46
47/// generated user access token length
48pub const TOKEN_LENGTH: usize = 32;
49
50/// Adds a new device to a user.
51///
52/// Without a device ID one is generated. A chosen ID is refused when longer
53/// than `MAX_DEVICE_ID_LENGTH` bytes or when it matches one of the user's
54/// cross-signing key IDs. The device is written and given its tokens under the
55/// device lock, where an expiring token without a refresh token retires any the
56/// ID already holds.
57#[implement(super::Service)]
58#[tracing::instrument(level = "debug", skip(self, access_token, refresh_token))]
59pub async fn create_device(
60	&self,
61	user_id: &UserId,
62	device_id: Option<&DeviceId>,
63	(access_token, expires_in): (Option<&str>, Option<Duration>),
64	refresh_token: Option<&str>,
65	initial_device_display_name: Option<&str>,
66	client_ip: Option<IpAddr>,
67) -> Result<OwnedDeviceId> {
68	let device_id = resolve_device_id(device_id);
69
70	if !self.exists(user_id).await {
71		return Err!(Request(InvalidParam(error!(
72			"Called create_device for non-existent user {user_id}"
73		))));
74	}
75
76	self.check_device_id(user_id, Some(&device_id))
77		.await?;
78
79	let lock = self.lock_device(user_id, &device_id).await;
80
81	let notify = true;
82
83	self.put_device_metadata(user_id, notify, &Device {
84		device_id: device_id.clone(),
85		display_name: initial_device_display_name.map(Into::into),
86		last_seen_ts: Some(MilliSecondsSinceUnixEpoch::now()),
87		last_seen_ip: client_ip.map(to_small_string),
88	})
89	.await;
90
91	if let Some(access_token) = access_token {
92		self.open_session(&lock, user_id, &device_id, (access_token, expires_in), refresh_token)
93			.await?;
94	}
95
96	Ok(device_id)
97}
98
99fn resolve_device_id(device_id: Option<&DeviceId>) -> OwnedDeviceId {
100	// Treat an empty device_id ("") as unspecified.
101	device_id
102		.filter(|device_id| !device_id.as_str().is_empty())
103		.map(ToOwned::to_owned)
104		.unwrap_or_else(|| OwnedDeviceId::from(random_string(DEVICE_ID_LENGTH)))
105}
106
107/// Refuses a device ID the user may not take.
108///
109/// An ID longer than `MAX_DEVICE_ID_LENGTH` bytes is refused. So is one
110/// coinciding with one of the user's cross-signing key IDs, since both share
111/// the device key row space. Without an ID nothing is refused.
112#[implement(super::Service)]
113pub async fn check_device_id(&self, user_id: &UserId, device_id: Option<&DeviceId>) -> Result {
114	let Some(device_id) = device_id.map(DeviceId::as_str) else {
115		return Ok(());
116	};
117
118	if device_id.len() > MAX_DEVICE_ID_LENGTH {
119		return Err!(Request(InvalidParam("Device ID is too long.")));
120	}
121
122	if self
123		.is_cross_signing_key_id(user_id, device_id)
124		.await?
125	{
126		return Err!(Request(Forbidden("Device ID matches a cross-signing key ID.")));
127	}
128
129	Ok(())
130}
131
132/// Locks one device against concurrent creation, token issuance, metadata
133/// and key updates, and removal.
134///
135/// A refresh token is rotated by reading the one the device points at and
136/// replacing it, so issuers run one after another to leave the device a single
137/// refresh token. An issuer, or a metadata or key update, that runs after
138/// removal finds no device rather than writing for one already gone.
139#[implement(super::Service)]
140pub(super) async fn lock_device(&self, user_id: &UserId, device_id: &DeviceId) -> DeviceLock {
141	let key = (user_id.to_owned(), device_id.to_owned());
142
143	self.updating_device.lock(&key).await
144}
145
146/// Issues the tokens that open a session on one device.
147///
148/// An expiring token given without a refresh token ends the session at its
149/// expiry, so any refresh token the device holds retires first. A rotation
150/// continues a session and keeps its refresh token on the grace path, so it
151/// never comes through here.
152#[implement(super::Service)]
153async fn open_session(
154	&self,
155	lock: &DeviceLock,
156	user_id: &UserId,
157	device_id: &DeviceId,
158	access: (&str, Option<Duration>),
159	refresh_token: Option<&str>,
160) -> Result {
161	let (_, expires_in) = access;
162
163	if expires_in.is_some() && refresh_token.is_none() {
164		self.remove_refresh_token(user_id, device_id)
165			.await?;
166	}
167
168	self.issue_tokens(lock, user_id, device_id, access, refresh_token)
169		.await
170}
171
172/// Removes every device of a user except the one to keep, if any.
173///
174/// Each device is removed as by `remove_device`, so its access token stops
175/// working. Removals run concurrently, in no particular order.
176#[implement(super::Service)]
177#[tracing::instrument(level = "debug", skip(self))]
178pub async fn remove_devices(&self, user_id: &UserId, keep: Option<&DeviceId>) {
179	self.all_device_ids(user_id)
180		.ready_filter(|&device_id| Some(device_id) != keep)
181		.map(ToOwned::to_owned)
182		.for_each_concurrent(automatic_width(), async |device_id| {
183			self.remove_device(user_id, &device_id).await;
184		})
185		.await;
186}
187
188/// Removes a device from a user.
189///
190/// Everything keyed by the device goes with it except its sync connections,
191/// so a later session under the same ID starts with no keys, identity keys
192/// included, and resumes its sync position.
193#[implement(super::Service)]
194#[tracing::instrument(level = "debug", skip(self))]
195pub async fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) {
196	let lock = self.lock_device(user_id, device_id).await;
197
198	self.remove_device_locked(&lock, user_id, device_id)
199		.await;
200}
201
202#[implement(super::Service)]
203// query-depth firewall
204#[async_noinline]
205async fn remove_device_locked<'a>(
206	&'a self,
207	_lock: &'a DeviceLock,
208	user_id: &'a UserId,
209	device_id: &'a DeviceId,
210) {
211	self.remove_tokens(user_id, device_id).await;
212
213	// Remove todevice events
214	self.db
215		.todeviceid_events
216		.del_prefix(&(user_id, device_id, Interfix))
217		.await;
218
219	// Remove pushers
220	self.services
221		.pusher
222		.get_device_pushkeys(user_id, device_id)
223		.map(Vec::into_iter)
224		.map(IterStream::stream)
225		.flatten_stream()
226		.for_each(async |pushkey| {
227			self.services
228				.pusher
229				.delete_pusher(user_id, &pushkey)
230				.await;
231		})
232		.await;
233
234	// Removes the dehydrated device if the ID matches, otherwise no-op
235	self.remove_dehydrated_device(user_id, Some(device_id))
236		.await
237		.ok();
238
239	self.remove_one_time_keys(user_id, device_id)
240		.await;
241
242	// MSC2732: drop fallback keys for this device.
243	self.db
244		.userdeviceidalgorithm_fallback
245		.del_prefix(&(user_id, device_id, Interfix))
246		.await;
247
248	// MSC3890: drop this device's local notification settings.
249	let event_type = format!("org.matrix.msc3890.local_notification_settings.{device_id}").into();
250	self.services
251		.account_data
252		.delete(None, user_id, event_type)
253		.await
254		.ok();
255
256	let userdeviceid = (user_id, device_id);
257
258	self.db.keyid_key.del(userdeviceid);
259	self.db.userdeviceid_metadata.del(userdeviceid);
260	self.db.oidcdevice_userdeviceid.del(userdeviceid);
261
262	self.mark_device_key_update(user_id, DeviceListChange::Deleted(device_id))
263		.await;
264}
265
266/// Returns an iterator over all device ids of this user.
267#[implement(super::Service)]
268pub fn all_device_ids<'a>(
269	&'a self,
270	user_id: &'a UserId,
271) -> impl Stream<Item = &DeviceId> + Send + 'a {
272	let prefix = (user_id, Interfix);
273	self.db
274		.userdeviceid_metadata
275		.keys_prefix(&prefix)
276		.ignore_err()
277		.map(|(_, device_id): (Ignore, &DeviceId)| device_id)
278}
279
280/// Find out which user a token belongs to, unless the token has expired.
281///
282/// An expired token stays recorded until its device moves on from it, so its
283/// client keeps reading a soft logout and a route granting access needs this
284/// rather than the plain lookup.
285#[implement(super::Service)]
286#[tracing::instrument(level = "debug", skip(self, token))]
287pub async fn find_from_unexpired_token(
288	&self,
289	token: &str,
290) -> Option<(OwnedUserId, OwnedDeviceId)> {
291	self.find_from_token(token)
292		.await
293		.ok()
294		.filter(|&(.., expires_at)| deadline_has_passed(expires_at).is_false())
295		.map(|(user_id, device_id, _)| (user_id, device_id))
296}
297
298/// Find out which user an access or refresh token belongs to.
299#[implement(super::Service)]
300#[tracing::instrument(level = "trace", skip(self, token))]
301pub async fn find_from_token(
302	&self,
303	token: &str,
304) -> Result<(OwnedUserId, OwnedDeviceId, Option<SystemTime>)> {
305	self.db
306		.token_userdeviceid
307		.get(token)
308		.await
309		.deserialized()
310		.and_then(|(user_id, device_id, expires_at): (_, _, Option<u64>)| {
311			let expires_at = expires_at
312				.map(Duration::from_secs)
313				.map(timepoint_from_epoch)
314				.transpose()?;
315
316			Ok((user_id, device_id, expires_at))
317		})
318}
319
320#[implement(super::Service)]
321#[tracing::instrument(level = "debug", skip(self))]
322pub async fn remove_tokens(&self, user_id: &UserId, device_id: &DeviceId) {
323	let remove_access = self
324		.remove_access_token(user_id, device_id)
325		.map(Result::ok);
326
327	let remove_refresh = self
328		.remove_refresh_token(user_id, device_id)
329		.map(Result::ok);
330
331	join(remove_access, remove_refresh).await;
332}
333
334/// Replaces the access token of one device, and its refresh token when one is
335/// given.
336///
337/// The tokens are issued under the device lock, and refused when the device no
338/// longer exists. An expiring token given without a refresh token is meant to
339/// end the session, so the device's own refresh token retires under that lock.
340#[implement(super::Service)]
341#[tracing::instrument(level = "debug", skip(self, access_token, refresh_token))]
342pub async fn set_access_token(
343	&self,
344	user_id: &UserId,
345	device_id: &DeviceId,
346	access_token: &str,
347	expires_in: Option<Duration>,
348	refresh_token: Option<&str>,
349) -> Result {
350	let lock = self.lock_device(user_id, device_id).await;
351
352	self.open_session(&lock, user_id, device_id, (access_token, expires_in), refresh_token)
353		.await
354}
355
356/// Exchanges a presented refresh token for a new access token of its device,
357/// returning the refresh token for the client to keep.
358///
359/// Reuse is judged by `seen`, the caller's classification when the request
360/// arrived: a token already spent outside the reuse grace window is refused,
361/// and its device revoked when so configured. Otherwise the token is classified
362/// again under the device lock, where a current one rotates and a spent one
363/// inside the grace window keeps its successor, each once `gate`, the caller's
364/// account check, passes. One found expired, or spent inside the grace window
365/// with an expired successor, is refused with the configured logout, and one
366/// spent meanwhile by a concurrent exchange is refused alone.
367#[implement(super::Service)]
368#[tracing::instrument(level = "debug", skip_all)]
369pub async fn rotate_refresh_token<Gate>(
370	&self,
371	seen: &RefreshToken,
372	presented: &str,
373	access: (&str, Option<Duration>),
374	gate: Gate,
375) -> Result<String>
376where
377	Gate: Future<Output = Result> + Send,
378{
379	let Some((user_id, device_id)) = seen.owner() else {
380		return Err!(Request(Forbidden("Refresh token is unrecognized.")));
381	};
382
383	let lock = self.lock_device(user_id, device_id).await;
384
385	if seen.reused() {
386		return self
387			.revoke_reused_refresh_token(&lock, user_id, device_id)
388			.map(Err)
389			.await;
390	}
391
392	let token = self
393		.classify_refresh_token(presented)
394		.map(|token| token.owned_by(user_id, device_id))
395		.await;
396
397	let exchangeable = token.exchangeable();
398	let kept = match token {
399		| RefreshToken::Unknown =>
400			return Err!(Request(Forbidden("Refresh token is unrecognized."))),
401
402		| RefreshToken::Current { .. } | RefreshToken::Replayed { grace: true, .. }
403			if !exchangeable =>
404			return self
405				.expire_refresh_token(&lock, user_id, device_id)
406				.map(Err)
407				.await,
408
409		| RefreshToken::Replayed { .. } if !exchangeable =>
410			return Err!(Request(Forbidden("Refresh token has already been used."))),
411
412		| RefreshToken::Current { .. } => None,
413		| RefreshToken::Replayed { current, .. } => Some(current),
414	};
415
416	gate.await?;
417
418	let rotated = kept.is_none();
419	let refresh_token = kept.unwrap_or_else(generate_refresh_token);
420
421	let rotated = rotated.then_some(refresh_token.as_str());
422
423	self.issue_tokens(&lock, user_id, device_id, access, rotated)
424		.await?;
425
426	Ok(refresh_token)
427}
428
429/// The user and device a recognized refresh token belongs to.
430///
431/// A spent token keeps naming its device, so a reuse can still be traced to
432/// it, while an unrecognized token has no owner.
433#[implement(RefreshToken)]
434#[must_use]
435pub fn owner(&self) -> Option<(&UserId, &DeviceId)> {
436	match self {
437		| Self::Current { user_id, device_id, .. }
438		| Self::Replayed { user_id, device_id, .. } => Some((user_id, device_id)),
439		| Self::Unknown => None,
440	}
441}
442
443/// Whether the token was presented again after its rotation, outside the reuse
444/// grace window.
445#[implement(RefreshToken)]
446#[must_use]
447pub fn reused(&self) -> bool { matches!(self, Self::Replayed { grace: false, .. }) }
448
449/// Narrows the classification to one device.
450///
451/// A token belonging to any other device is unknown to it.
452#[implement(RefreshToken)]
453fn owned_by(self, user_id: &UserId, device_id: &DeviceId) -> Self {
454	let owned = self.owner() == Some((user_id, device_id));
455
456	owned.then_some(self).unwrap_or(Self::Unknown)
457}
458
459/// Whether the token may be exchanged for new tokens as classified.
460///
461/// A current token qualifies until it expires, and a spent one only inside the
462/// reuse grace window and until its successor expires.
463#[implement(RefreshToken)]
464#[must_use]
465pub fn exchangeable(&self) -> bool {
466	match self {
467		| Self::Current { expires_at, .. } | Self::Replayed { grace: true, expires_at, .. } =>
468			deadline_has_passed(*expires_at).is_false(),
469
470		| Self::Replayed { .. } | Self::Unknown => false,
471	}
472}
473
474/// Refuses an expired refresh token, retiring it first.
475///
476/// With hard logout the whole device is removed, otherwise only its refresh
477/// token, leaving the session to log in again on the same device.
478#[implement(super::Service)]
479async fn expire_refresh_token(
480	&self,
481	lock: &DeviceLock,
482	user_id: &UserId,
483	device_id: &DeviceId,
484) -> Error {
485	let config = &self.services.server.config;
486	let hard = config.authentication.refresh_token.hard_logout;
487
488	hard.then_async(|| self.remove_device_locked(lock, user_id, device_id))
489		.unwrap_or_else_async(async || {
490			self.remove_refresh_token(user_id, device_id)
491				.await
492				.ok();
493		})
494		.await;
495
496	Error::unknown_token(!hard, "Refresh token has expired.")
497}
498
499/// Refuses a refresh token presented again after its rotation.
500///
501/// Reuse outside the grace window suggests the token was copied, so the device
502/// is removed when `authentication.refresh_token.reuse_revoke` is set.
503#[implement(super::Service)]
504async fn revoke_reused_refresh_token(
505	&self,
506	lock: &DeviceLock,
507	user_id: &UserId,
508	device_id: &DeviceId,
509) -> Error {
510	let config = &self.services.server.config;
511	let revoke = config.authentication.refresh_token.reuse_revoke;
512
513	if revoke {
514		warn!(%user_id, %device_id, "Revoking a device whose refresh token was reused.");
515		self.remove_device_locked(lock, user_id, device_id)
516			.await;
517	} else {
518		debug_warn!(%user_id, %device_id, "Refresh token reused after rotation.");
519	}
520
521	Error::unknown_token(!revoke, "Refresh token has already been used.")
522}
523
524/// Issues an access token, and a refresh token when one is given, to one
525/// device.
526///
527/// A device removed before its lock was taken gets none.
528#[implement(super::Service)]
529async fn issue_tokens(
530	&self,
531	lock: &DeviceLock,
532	user_id: &UserId,
533	device_id: &DeviceId,
534	(access_token, expires_in): (&str, Option<Duration>),
535	refresh_token: Option<&str>,
536) -> Result {
537	assert!(
538		access_token.len() >= TOKEN_LENGTH,
539		"Caller must supply an access_token >= {TOKEN_LENGTH} chars."
540	);
541
542	if !self.device_exists(user_id, device_id).await {
543		return Err!(Request(Forbidden("Cannot issue tokens for a removed device.")));
544	}
545
546	if let Some(refresh_token) = refresh_token {
547		self.set_refresh_token(lock, user_id, device_id, refresh_token)
548			.await?;
549	}
550
551	let expires_at = expires_in
552		.map(timepoint_from_now)
553		.transpose()?
554		.map(duration_since_epoch)
555		.as_ref()
556		.map(Duration::as_secs);
557
558	let userdeviceid = (user_id, device_id);
559
560	// Fold the prior pointer token into the index for pre-index upgrades.
561	let previous = self
562		.db
563		.userdeviceid_token
564		.qry(&userdeviceid)
565		.await
566		.deserialized::<String>()
567		.ok();
568
569	let superseded = self
570		.superseded_access_tokens(user_id, device_id)
571		.await;
572
573	self.write_access_token(
574		user_id,
575		device_id,
576		(access_token, expires_at),
577		previous.as_deref(),
578		superseded,
579	);
580
581	Ok(())
582}
583
584/// Stores an access token in one write, with the index rows of the token it
585/// replaces and the removal of the superseded tokens.
586///
587/// The token being replaced stays whatever its expiry, since requests may still
588/// carry it.
589#[implement(super::Service)]
590fn write_access_token(
591	&self,
592	user_id: &UserId,
593	device_id: &DeviceId,
594	(access_token, expires_at): (&str, Option<u64>),
595	previous: Option<&str>,
596	superseded: impl Iterator<Item = AccessToken>,
597) {
598	let userdeviceid = (user_id, device_id);
599	let mut txn = self.services.db.txn();
600
601	if let Some(previous) = previous {
602		let key = (user_id, device_id, previous);
603
604		txn.put_raw(&self.db.userdeviceidtoken_index, key, []);
605	}
606
607	superseded
608		.filter(|token| Some(token.as_str()) != previous)
609		.for_each(|token| {
610			txn.del_raw(&self.db.token_userdeviceid, &token);
611			txn.del(&self.db.userdeviceidtoken_index, (user_id, device_id, token.as_str()));
612		});
613
614	let key = (user_id, device_id, access_token);
615	let value = (user_id, device_id, expires_at);
616
617	txn.raw_put(&self.db.token_userdeviceid, access_token, value);
618	txn.put_raw(&self.db.userdeviceidtoken_index, key, []);
619	txn.put_raw(&self.db.userdeviceid_token, userdeviceid, access_token);
620
621	txn.execute();
622}
623
624/// Finds the expired access tokens of one device, except those with the latest
625/// expiry.
626///
627/// Issuing a token forgets these, which keeps the device's rows from growing.
628/// A later token having expired shows the client moved on, so forgetting the
629/// older one should not turn a request still in flight into a hard logout. A
630/// token with no expiry, or whose row cannot be read, is never included.
631#[implement(super::Service)]
632#[tracing::instrument(level = "debug", skip(self))]
633async fn superseded_access_tokens(
634	&self,
635	user_id: &UserId,
636	device_id: &DeviceId,
637) -> impl Iterator<Item = AccessToken> {
638	let prefix = (user_id, device_id, Interfix);
639	let expired: ExpiredTokens = self
640		.db
641		.userdeviceidtoken_index
642		.keys_prefix(&prefix)
643		.ignore_err()
644		.map(|(_, _, token): (Ignore, Ignore, &str)| AccessToken::from(token))
645		.broad_filter_map(async |token| {
646			self.find_from_token(&token)
647				.await
648				.ok()
649				.and_then(at!(2))
650				.filter(|&expires_at| timepoint_has_passed(expires_at))
651				.map(|expires_at| (expires_at, token))
652		})
653		.collect()
654		.await;
655
656	let newest = expired.iter().map(at!(0)).max();
657
658	expired
659		.into_iter()
660		.filter(move |(expires_at, _)| Some(*expires_at) < newest)
661		.map(at!(1))
662}
663
664/// Revoke every access token of one device, without deleting the device. Take
665/// care to not leave dangling devices if using this method.
666#[implement(super::Service)]
667pub async fn remove_access_token(&self, user_id: &UserId, device_id: &DeviceId) -> Result {
668	let prefix = (user_id, device_id, Interfix);
669	self.db
670		.userdeviceidtoken_index
671		.keys_prefix(&prefix)
672		.ignore_err()
673		.ready_for_each(|(_, _, token): (Ignore, Ignore, &str)| {
674			self.db.token_userdeviceid.remove(token);
675			self.db
676				.userdeviceidtoken_index
677				.del((user_id, device_id, token));
678		})
679		.await;
680
681	// Cover any pre-index token still recorded only in the legacy pointer.
682	let token = self
683		.db
684		.userdeviceid_token
685		.qry(&(user_id, device_id))
686		.await
687		.deserialized::<String>()
688		.ok();
689
690	let mut txn = self.services.db.txn();
691
692	if let Some(token) = token.as_deref() {
693		txn.del_raw(&self.db.token_userdeviceid, token);
694	}
695
696	txn.del(&self.db.userdeviceid_token, (user_id, device_id));
697
698	txn.execute();
699
700	Ok(())
701}
702
703#[implement(super::Service)]
704pub fn generate_access_token(&self, expires: bool) -> (String, Option<Duration>) {
705	let access_token = random_string(TOKEN_LENGTH);
706	let ttl = self
707		.services
708		.server
709		.config
710		.authentication
711		.access_token_ttl;
712
713	let expires_in = expires.then_some(ttl).map(Duration::from_secs);
714
715	(access_token, expires_in)
716}
717
718/// Replaces the refresh token of one device in a single write.
719///
720/// The outgoing token is retired in the same batch that stores its successor,
721/// so a token presented meanwhile classifies as current or as spent, never as
722/// unknown. Absolute expiry carries the prior deadline forward.
723#[implement(super::Service)]
724#[tracing::instrument(level = "debug", skip(self, _lock, refresh_token))]
725async fn set_refresh_token(
726	&self,
727	_lock: &DeviceLock,
728	user_id: &UserId,
729	device_id: &DeviceId,
730	refresh_token: &str,
731) -> Result {
732	debug_assert!(refresh_token.starts_with("refresh_"), "refresh_token missing prefix");
733
734	let config = &self.services.server.config;
735	let ttl = config.authentication.refresh_token.ttl;
736	let idle_only = config.authentication.refresh_token.idle_only;
737	let userdeviceid = (user_id, device_id);
738	let outgoing = self
739		.db
740		.userdeviceid_refresh
741		.qry(&userdeviceid)
742		.await
743		.ok();
744
745	// Absolute mode carries the prior deadline forward instead of sliding it.
746	let prior_expires_at = outgoing
747		.as_deref()
748		.filter(|_| ttl != 0 && !idle_only)
749		.map_async(|outgoing| self.find_refresh_token_expires_at(outgoing))
750		.await
751		.flatten();
752
753	let expires_at = match (ttl, prior_expires_at) {
754		| (0, _) => None,
755		| (_, Some(prior)) => Some(prior),
756		| (ttl, None) => Some(timepoint_from_now(Duration::from_secs(ttl))?),
757	};
758
759	let expires_at_secs = expires_at
760		.map(duration_since_epoch)
761		.as_ref()
762		.map(Duration::as_secs);
763
764	let value = (user_id, device_id, expires_at_secs);
765	let mut txn = self.services.db.txn();
766
767	if let Some(outgoing) = outgoing.as_deref() {
768		txn.del_raw(&self.db.token_userdeviceid, outgoing);
769	}
770
771	// Queued before the spent pointer below is rewritten; the batch applies in order.
772	self.forget_spent_refresh_token(user_id, device_id, &mut txn)
773		.await;
774
775	txn.raw_put(&self.db.token_userdeviceid, refresh_token, value);
776	txn.put_raw(&self.db.userdeviceid_refresh, userdeviceid, refresh_token);
777
778	// Retain the outgoing token as the device's spent token, pointing at its
779	// successor so a double-submit can be distinguished from a replay.
780	if let Some(spent) = outgoing.as_deref() {
781		let spent_at = duration_since_epoch(SystemTime::now()).as_secs();
782		let value = (user_id, device_id, refresh_token, spent_at);
783
784		txn.raw_put(&self.db.spentrefresh_userdeviceid, spent, value);
785		txn.put_raw(&self.db.userdeviceid_spentrefresh, userdeviceid, spent);
786	}
787
788	txn.execute();
789
790	Ok(())
791}
792
793/// Looks up the expiry stored alongside a refresh token.
794///
795/// Pre-rotation entries carry no expiry and return `None`.
796#[implement(super::Service)]
797async fn find_refresh_token_expires_at(&self, token: &[u8]) -> Option<SystemTime> {
798	let (_, _, expires_at_secs): (Ignore, Ignore, Option<u64>) = self
799		.db
800		.token_userdeviceid
801		.get(token)
802		.await
803		.deserialized()
804		.ok()?;
805
806	expires_at_secs
807		.map(Duration::from_secs)
808		.map(timepoint_from_epoch)?
809		.ok()
810}
811
812/// Revoke the refresh token without deleting the device. Take care to not leave
813/// dangling devices if using this method.
814#[implement(super::Service)]
815pub async fn remove_refresh_token(&self, user_id: &UserId, device_id: &DeviceId) -> Result {
816	let userdeviceid = (user_id, device_id);
817	let refresh_token = self
818		.db
819		.userdeviceid_refresh
820		.qry(&userdeviceid)
821		.await;
822
823	let mut txn = self.services.db.txn();
824
825	if let Ok(refresh_token) = refresh_token {
826		txn.del_raw(&self.db.token_userdeviceid, &refresh_token);
827	}
828
829	txn.del(&self.db.userdeviceid_refresh, userdeviceid);
830
831	self.forget_spent_refresh_token(user_id, device_id, &mut txn)
832		.await;
833
834	txn.execute();
835
836	Ok(())
837}
838
839/// Drop the spent (previous-generation) refresh token retained for reuse
840/// detection, if any.
841#[implement(super::Service)]
842async fn forget_spent_refresh_token(
843	&self,
844	user_id: &UserId,
845	device_id: &DeviceId,
846	txn: &mut Txn,
847) {
848	let userdeviceid = (user_id, device_id);
849
850	if let Ok(spent) = self
851		.db
852		.userdeviceid_spentrefresh
853		.qry(&userdeviceid)
854		.await
855	{
856		txn.del_raw(&self.db.spentrefresh_userdeviceid, &spent);
857	}
858
859	txn.del(&self.db.userdeviceid_spentrefresh, userdeviceid);
860}
861
862/// Classification of a refresh token presented for rotation at a token
863/// endpoint.
864///
865/// A token endpoint classifies the token on arrival to find its device, and the
866/// exchange classifies it again under that device's lock.
867pub enum RefreshToken {
868	/// The device's current refresh token; rotate it.
869	Current {
870		/// The user the token was issued to.
871		user_id: OwnedUserId,
872
873		/// The device the token was issued to.
874		device_id: OwnedDeviceId,
875
876		/// The token's deadline, past which it is no longer exchangeable.
877		expires_at: Option<SystemTime>,
878	},
879
880	/// A spent (already-rotated) token retained for one generation.
881	Replayed {
882		/// The user the token was issued to.
883		user_id: OwnedUserId,
884
885		/// The device the token was issued to.
886		device_id: OwnedDeviceId,
887
888		/// The successor, for which to re-issue an access token.
889		current: String,
890
891		/// The successor's deadline, past which this token is no longer
892		/// exchangeable; read only when `grace` is set.
893		expires_at: Option<SystemTime>,
894
895		/// Set when the successor is still current and this token was spent
896		/// within the configured window, marking a benign double-submit rather
897		/// than a replay.
898		grace: bool,
899	},
900
901	/// Not a recognised refresh token.
902	Unknown,
903}
904
905/// Classify a presented refresh token for the token-endpoint rotation path.
906///
907/// A current token carries its own expiry, and the one retained spent token its
908/// successor, with that successor's expiry when `grace` is set. A grace replay
909/// whose successor no longer resolves is unknown, as is anything else.
910#[implement(super::Service)]
911pub async fn classify_refresh_token(&self, presented: &str) -> RefreshToken {
912	// The current refresh token resolves and matches the device's active
913	// pointer (an access token resolves but will not match).
914	if let Ok((user_id, device_id, expires_at)) = self.find_from_token(presented).await {
915		let current: Option<String> = self
916			.db
917			.userdeviceid_refresh
918			.qry(&(&user_id, &device_id))
919			.await
920			.deserialized()
921			.ok();
922
923		if current.as_deref() == Some(presented) {
924			return RefreshToken::Current { user_id, device_id, expires_at };
925		}
926	}
927
928	// Otherwise it may be the one retained spent token: a benign double-submit
929	// inside the grace window, or a replay to be treated as a compromise.
930	let Ok((user_id, device_id, successor, spent_at)) = self
931		.db
932		.spentrefresh_userdeviceid
933		.get(presented)
934		.await
935		.deserialized::<(OwnedUserId, OwnedDeviceId, String, u64)>()
936	else {
937		return RefreshToken::Unknown;
938	};
939
940	let current: Option<String> = self
941		.db
942		.userdeviceid_refresh
943		.qry(&(&user_id, &device_id))
944		.await
945		.deserialized()
946		.ok();
947
948	let grace_window = self
949		.services
950		.server
951		.config
952		.authentication
953		.refresh_token
954		.reuse_grace;
955
956	let elapsed = duration_since_epoch(SystemTime::now())
957		.as_secs()
958		.saturating_sub(spent_at);
959
960	let grace = grace_window != 0
961		&& elapsed <= grace_window
962		&& current.as_deref() == Some(successor.as_str());
963
964	// A successor that no longer resolves makes this unknown, as presenting it would.
965	let Ok(resolved) = grace
966		.then_async(|| self.find_from_token(&successor))
967		.map(Option::transpose)
968		.await
969	else {
970		return RefreshToken::Unknown;
971	};
972
973	RefreshToken::Replayed {
974		user_id,
975		device_id,
976		current: successor,
977		expires_at: resolved.and_then(at!(2)),
978		grace,
979	}
980}
981
982#[must_use]
983pub fn generate_refresh_token() -> String { format!("refresh_{}", random_string(TOKEN_LENGTH)) }
984
985#[implement(super::Service)]
986pub fn add_to_device_event(
987	&self,
988	sender: &UserId,
989	target_user_id: &UserId,
990	target_device_id: &DeviceId,
991	event_type: &str,
992	content: &serde_json::Value,
993) -> u64 {
994	let count = self.services.globals.next_count();
995
996	let key = (target_user_id, target_device_id, *count);
997	self.db.todeviceid_events.put(
998		key,
999		Json(json!({
1000			"type": event_type,
1001			"sender": sender,
1002			"content": content,
1003		})),
1004	);
1005
1006	trace!(
1007		%target_user_id,
1008		%target_device_id,
1009		count = *count,
1010		%event_type,
1011		%sender,
1012		"to_device write",
1013	);
1014
1015	*count
1016}
1017
1018#[implement(super::Service)]
1019pub fn get_to_device_events<'a>(
1020	&'a self,
1021	user_id: &'a UserId,
1022	device_id: &'a DeviceId,
1023	since: Option<u64>,
1024	to: Option<u64>,
1025) -> impl Stream<Item = (u64, Raw<AnyToDeviceEvent>)> + Send + 'a {
1026	type Key<'a> = (&'a UserId, &'a DeviceId, u64);
1027
1028	let from = (user_id, device_id, since.map_or(0, |since| since.saturating_add(1)));
1029
1030	self.db
1031		.todeviceid_events
1032		.stream_from(&from)
1033		.ignore_err()
1034		.ready_take_while(move |((user_id_, device_id_, count), _): &(Key<'_>, _)| {
1035			user_id == *user_id_ && device_id == *device_id_ && to.is_none_or(|to| *count <= to)
1036		})
1037		.map(|((_, _, count), event)| (count, event))
1038}
1039
1040#[implement(super::Service)]
1041pub async fn remove_to_device_events<Until>(
1042	&self,
1043	user_id: &UserId,
1044	device_id: &DeviceId,
1045	until: Until,
1046) where
1047	Until: Into<Option<u64>> + Send,
1048{
1049	type Key<'a> = (&'a UserId, &'a DeviceId, u64);
1050
1051	let until = until.into().unwrap_or(u64::MAX);
1052	let from = (user_id, device_id, until);
1053	self.db
1054		.todeviceid_events
1055		.rev_keys_from(&from)
1056		.ignore_err()
1057		.ready_take_while(move |(user_id_, device_id_, _): &Key<'_>| {
1058			user_id == *user_id_ && device_id == *device_id_
1059		})
1060		.ready_for_each(|key: Key<'_>| {
1061			self.db.todeviceid_events.del(key);
1062		})
1063		.await;
1064}
1065
1066/// Records when and from where a device was last seen.
1067///
1068/// An address is kept from an earlier sighting when none is given, and the
1069/// time defaults to now. The device list is not notified.
1070#[implement(super::Service)]
1071pub async fn update_device_last_seen(
1072	&self,
1073	user_id: &UserId,
1074	device_id: &DeviceId,
1075	last_seen_ip: Option<IpAddr>,
1076	last_seen_ts: Option<MilliSecondsSinceUnixEpoch>,
1077) -> Result {
1078	self.update_device_metadata(user_id, device_id, |device| {
1079		let last_seen_ip = last_seen_ip
1080			.map(to_small_string)
1081			.or(device.last_seen_ip);
1082
1083		let last_seen_ts = last_seen_ts
1084			.unwrap_or_else(MilliSecondsSinceUnixEpoch::now)
1085			.into();
1086
1087		let device = Device { last_seen_ip, last_seen_ts, ..device };
1088		let notify = false;
1089
1090		(device, notify)
1091	})
1092	.await
1093}
1094
1095/// Renames an existing device, notifying its device list only when the name
1096/// changes.
1097///
1098/// The rename holds the device lock like any other metadata update.
1099#[implement(super::Service)]
1100pub async fn rename_device(
1101	&self,
1102	user_id: &UserId,
1103	device_id: &DeviceId,
1104	display_name: &str,
1105) -> Result {
1106	self.update_device_metadata(user_id, device_id, |device| {
1107		let notify = device.display_name.as_deref() != Some(display_name);
1108		let device = Device {
1109			display_name: Some(display_name.into()),
1110			..device
1111		};
1112
1113		(device, notify)
1114	})
1115	.await
1116}
1117
1118/// Rewrites the metadata of an existing device, notifying its device list when
1119/// `update` says so.
1120///
1121/// The read and the write hold the device lock, so a device removed in between
1122/// is not written back, and two updates never lose one another's fields. A
1123/// missing device is an error and `update` does not run. `update` must keep the
1124/// device ID; changing it panics.
1125#[implement(super::Service)]
1126#[tracing::instrument(level = "trace", skip(self, update))]
1127pub async fn update_device_metadata<Update>(
1128	&self,
1129	user_id: &UserId,
1130	device_id: &DeviceId,
1131	update: Update,
1132) -> Result
1133where
1134	Update: FnOnce(Device) -> (Device, bool) + Send,
1135{
1136	let _lock = self.lock_device(user_id, device_id).await;
1137
1138	let device = self
1139		.get_device_metadata(user_id, device_id)
1140		.await?;
1141
1142	let (device, notify) = update(device);
1143
1144	assert_eq!(&device.device_id, device_id, "update must keep the device ID");
1145	self.put_device_metadata(user_id, notify, &device)
1146		.await;
1147
1148	Ok(())
1149}
1150
1151/// Persists device metadata and optionally announces the changed device.
1152///
1153/// Silent updates leave the device-list version and notification rows unchanged.
1154#[implement(super::Service)]
1155#[tracing::instrument(level = "trace", skip(self, device))]
1156async fn put_device_metadata(&self, user_id: &UserId, notify: bool, device: &Device) {
1157	let key = (user_id, &device.device_id);
1158	self.db
1159		.userdeviceid_metadata
1160		.put(key, Json(device));
1161
1162	if notify {
1163		self.mark_device_key_update(user_id, DeviceListChange::Device(&device.device_id))
1164			.boxed() // Size firewall for device creation and rename callers.
1165			.await;
1166	}
1167}
1168
1169/// Get device metadata.
1170#[implement(super::Service)]
1171pub async fn get_device_metadata(
1172	&self,
1173	user_id: &UserId,
1174	device_id: &DeviceId,
1175) -> Result<Device> {
1176	self.db
1177		.userdeviceid_metadata
1178		.qry(&(user_id, device_id))
1179		.await
1180		.deserialized()
1181		.inspect(|device: &Device| {
1182			debug_assert_eq!(&device.device_id, device_id, "device_id mismatch");
1183		})
1184}
1185
1186#[implement(super::Service)]
1187pub async fn device_exists(&self, user_id: &UserId, device_id: &DeviceId) -> bool {
1188	self.db
1189		.userdeviceid_metadata
1190		.contains(&(user_id, device_id))
1191		.await
1192}
1193
1194/// Whether a device exists, returning a failed read instead of taking it for
1195/// absence.
1196///
1197/// Callers that act on a device's absence use this, since `device_exists`
1198/// reports a device it cannot read as absent.
1199#[implement(super::Service)]
1200pub async fn try_device_exists(&self, user_id: &UserId, device_id: &DeviceId) -> Result<bool> {
1201	self.db
1202		.userdeviceid_metadata
1203		.try_contains(&(user_id, device_id))
1204		.await
1205}
1206
1207#[implement(super::Service)]
1208pub async fn is_oidc_device(&self, user_id: &UserId, device_id: &DeviceId) -> bool {
1209	self.db
1210		.oidcdevice_userdeviceid
1211		.contains(&(user_id, device_id))
1212		.await
1213}
1214
1215/// Returns the IdP that originally authenticated this device, if known.
1216/// Returns `None` for devices predating the idp_id field or non-OIDC devices.
1217#[implement(super::Service)]
1218pub async fn get_oidc_device_idp(
1219	&self,
1220	user_id: &UserId,
1221	device_id: &DeviceId,
1222) -> Option<String> {
1223	self.db
1224		.oidcdevice_userdeviceid
1225		.qry(&(user_id, device_id))
1226		.await
1227		.deserialized::<Json<String>>()
1228		.ok()
1229		.map(|Json(idp)| idp)
1230		.filter(|idp| !idp.is_empty())
1231}
1232
1233#[implement(super::Service)]
1234pub fn mark_oidc_device(&self, user_id: &UserId, device_id: &DeviceId, idp_id: &str) {
1235	self.db
1236		.oidcdevice_userdeviceid
1237		.put((user_id, device_id), Json(idp_id));
1238}
1239
1240/// Allow cross-signing key replacement without UIAA for the next 10 minutes.
1241/// Returns the expiry timestamp in milliseconds.
1242#[expect(clippy::must_use_candidate)]
1243#[implement(super::Service)]
1244pub fn allow_cross_signing_replacement(&self, user_id: &UserId) -> SystemTime {
1245	let duration = Duration::from_mins(10);
1246	let expires = timepoint_from_now(duration).expect("failed to create timepoint from now");
1247
1248	self.db
1249		.oidccskeybypass_userid
1250		.raw_put(user_id, Cbor(expires));
1251
1252	expires
1253}
1254
1255/// Check if the user is allowed to replace cross-signing keys without UIAA.
1256#[implement(super::Service)]
1257pub async fn can_replace_cross_signing_keys(&self, user_id: &UserId) -> bool {
1258	let Ok(expires): Result<SystemTime, _> = self
1259		.db
1260		.oidccskeybypass_userid
1261		.get(user_id)
1262		.await
1263		.deserialized::<Cbor<_>>()
1264		.map(at!(0))
1265	else {
1266		return false;
1267	};
1268
1269	if !timepoint_has_passed(expires) {
1270		return true;
1271	}
1272
1273	self.db.oidccskeybypass_userid.remove(user_id);
1274	false
1275}
1276
1277#[implement(super::Service)]
1278pub async fn get_devicelist_version(&self, user_id: &UserId) -> Result<u64> {
1279	self.db
1280		.userid_devicelistversion
1281		.get(user_id)
1282		.await
1283		.deserialized()
1284}
1285
1286#[implement(super::Service)]
1287pub fn all_devices_metadata<'a>(
1288	&'a self,
1289	user_id: &'a UserId,
1290) -> impl Stream<Item = Device> + Send + 'a {
1291	let key = (user_id, Interfix);
1292	self.db
1293		.userdeviceid_metadata
1294		.stream_prefix(&key)
1295		.ignore_err()
1296		.map(|(_, val): (Ignore, Device)| val)
1297}
1298
1299#[cfg(test)]
1300mod tests {
1301	use super::*;
1302
1303	#[test]
1304	fn absent_device_id_is_generated() {
1305		let device_id = resolve_device_id(None);
1306
1307		assert_eq!(device_id.as_str().len(), DEVICE_ID_LENGTH);
1308	}
1309
1310	#[test]
1311	fn empty_device_id_is_generated() {
1312		let device_id = resolve_device_id(Some("".into()));
1313
1314		assert_eq!(device_id.as_str().len(), DEVICE_ID_LENGTH);
1315	}
1316
1317	#[test]
1318	fn provided_device_id_is_preserved() {
1319		let device_id = resolve_device_id(Some("HELLOWORLD".into()));
1320
1321		assert_eq!(device_id.as_str(), "HELLOWORLD");
1322	}
1323}