Skip to main content

tuwunel_service/users/
dehydrated_device.rs

1use ruma::{
2	DeviceId, OwnedDeviceId, UserId,
3	api::client::dehydrated_device::{
4		DehydratedDeviceData, put_dehydrated_device::unstable::Request,
5	},
6	serde::Raw,
7};
8use serde::{Deserialize, Serialize};
9use tuwunel_core::{Err, Result, implement, trace};
10use tuwunel_database::{Deserialized, Json};
11
12#[derive(Clone, Debug, Serialize, Deserialize)]
13pub struct DehydratedDevice {
14	/// Unique ID of the device.
15	pub device_id: OwnedDeviceId,
16
17	/// Contains serialized and encrypted private data.
18	pub device_data: Raw<DehydratedDeviceData>,
19}
20
21/// Creates or recreates the user's dehydrated device.
22#[implement(super::Service)]
23#[tracing::instrument(
24	level = "info",
25	skip_all,
26	fields(
27		%user_id,
28		device_id = %request.device_id,
29		display_name = ?request.initial_device_display_name,
30	)
31)]
32pub async fn set_dehydrated_device(&self, user_id: &UserId, request: Request) -> Result {
33	assert!(
34		self.exists(user_id).await,
35		"Tried to create dehydrated device for non-existent user"
36	);
37
38	let existing_id = self.get_dehydrated_device_id(user_id).await;
39
40	if existing_id.is_err()
41		&& self
42			.device_exists(user_id, &request.device_id)
43			.await
44	{
45		return Err!("A hydrated device already exists with that ID.");
46	}
47
48	// Checked before removing the existing device, so a refused replacement
49	// leaves it in place.
50	self.check_device_id(user_id, Some(&request.device_id))
51		.await?;
52
53	if let Ok(existing_id) = existing_id {
54		self.remove_device(user_id, &existing_id).await;
55	}
56
57	let device_id = self
58		.create_device(
59			user_id,
60			Some(&request.device_id),
61			(None, None),
62			None,
63			request.initial_device_display_name.as_deref(),
64			None,
65		)
66		.await?;
67
68	trace!(device_data = ?request.device_data);
69	self.db.userid_dehydrateddevice.raw_put(
70		user_id,
71		Json(&DehydratedDevice {
72			device_id: device_id.clone(),
73			device_data: request.device_data,
74		}),
75	);
76
77	trace!(device_keys = ?request.device_keys);
78	self.add_device_keys(user_id, &device_id, &request.device_keys)
79		.await?;
80
81	trace!(one_time_keys = ?request.one_time_keys);
82	self.add_one_time_keys(
83		user_id,
84		&device_id,
85		&request.one_time_keys,
86		request.one_time_keys.len(),
87	)
88	.await?;
89
90	// MSC3814: dehydrated device MUST be cross-signed and have a fallback key.
91	trace!(fallback_keys = ?request.fallback_keys);
92	self.add_fallback_keys(
93		user_id,
94		&device_id,
95		request
96			.fallback_keys
97			.iter()
98			.map(|(id, key)| (id.as_ref(), key)),
99	)
100	.await?;
101
102	Ok(())
103}
104
105/// Removes a user's dehydrated device.
106///
107/// Calling this directly will remove the dehydrated data but leak the frontage
108/// device. Thus this is called by the regular device interface such that the
109/// dehydrated data will not leak instead.
110///
111/// If device_id is given, the user's dehydrated device must match or this is a
112/// no-op, but an Err is still returned to indicate that. Otherwise returns the
113/// removed dehydrated device_id.
114#[implement(super::Service)]
115#[tracing::instrument(
116	level = "debug",
117	skip_all,
118	fields(
119		%user_id,
120		device_id = ?maybe_device_id,
121	)
122)]
123pub(super) async fn remove_dehydrated_device(
124	&self,
125	user_id: &UserId,
126	maybe_device_id: Option<&DeviceId>,
127) -> Result<OwnedDeviceId> {
128	let Ok(device_id) = self.get_dehydrated_device_id(user_id).await else {
129		return Err!(Request(NotFound("No dehydrated device for this user.")));
130	};
131
132	if let Some(maybe_device_id) = maybe_device_id
133		&& maybe_device_id != device_id
134	{
135		return Err!(Request(NotFound("Not the user's dehydrated device.")));
136	}
137
138	self.db.userid_dehydrateddevice.remove(user_id);
139
140	Ok(device_id)
141}
142
143/// Get the device_id of the user's dehydrated device.
144#[implement(super::Service)]
145#[tracing::instrument(
146	level = "debug",
147	skip_all,
148	fields(%user_id)
149)]
150pub async fn get_dehydrated_device_id(&self, user_id: &UserId) -> Result<OwnedDeviceId> {
151	self.get_dehydrated_device(user_id)
152		.await
153		.map(|device| device.device_id)
154}
155
156/// Get the dehydrated device private data
157#[implement(super::Service)]
158#[tracing::instrument(
159	level = "debug",
160	skip_all,
161	fields(%user_id),
162	ret,
163)]
164pub async fn get_dehydrated_device(&self, user_id: &UserId) -> Result<DehydratedDevice> {
165	self.db
166		.userid_dehydrateddevice
167		.get(user_id)
168		.await
169		.deserialized::<String>()
170		.and_then(|raw| serde_json::from_str(&raw).map_err(Into::into))
171}