tuwunel_service/profile/
remote.rs1use std::borrow::Cow;
2
3use futures::{StreamExt, TryStreamExt};
4use ruma::{
5 UserId,
6 api::federation::query::get_profile_information::v1::{Request, Response},
7 profile::ProfileFieldName,
8};
9use serde_json::Value;
10use tuwunel_core::{
11 Err, Result, implement,
12 smallvec::SmallVec,
13 utils::{
14 json::serialized_len,
15 stream::{IterStream, TryReadyExt},
16 },
17};
18use tuwunel_database::{Ignore, Interfix, Json};
19
20use super::{MAX_PROFILE_SIZE, Propagation, ProspectiveProfile, Service, check_profile_key};
21
22type Removed = SmallVec<[ProfileFieldName; 1]>;
23
24type Fields = SmallVec<[(ProfileFieldName, Option<Value>); 2]>;
25
26#[implement(Service)]
31#[tracing::instrument(level = "debug", skip_all, fields(%user_id))]
32pub(super) async fn merge_profile(&self, user_id: &UserId, response: Response) -> Result {
33 let max_fields = self.services.config.profile.max_remote_fields;
34
35 check_served_profile(&response, max_fields)?;
36
37 let profile_lock = self.mutex.lock(user_id).await;
38 let incoming = response
39 .iter()
40 .map(|(name, value)| (name.as_str().into(), Cow::Borrowed(value)))
41 .try_stream();
42
43 let prospective: ProspectiveProfile<'_> = self
44 .useridprofilekey_value
45 .stream_prefix(&(user_id, Interfix))
46 .map_ok(|((_, name), Json(value)): ((Ignore, &str), Json<Value>)| {
47 (name.into(), Cow::Owned(value))
48 })
49 .chain(incoming)
50 .try_collect()
51 .await?;
52
53 check_field_count(prospective.len(), max_fields)?;
54
55 prospective
56 .keys()
57 .try_for_each(|name| check_profile_key(name.as_str()))?;
58
59 if serialized_len(&prospective)? > MAX_PROFILE_SIZE {
60 return Err!(Request(ProfileTooLarge(
61 "Profile would exceed the maximum size of 64 KiB."
62 )));
63 }
64
65 if !self.services.users.exists(user_id).await {
66 self.services
67 .users
68 .create(user_id, None, None)
69 .await?;
70 }
71
72 let fields: Fields = response
73 .into_iter()
74 .map(|(name, value)| (name.into(), Some(value)))
75 .collect();
76
77 self.set_profile_keys_locked(&profile_lock, user_id, &fields, Some(Propagation::None))
78 .await
79}
80
81#[implement(Service)]
88#[tracing::instrument(
89 level = "debug",
90 skip_all,
91 fields(
92 %user_id,
93 ),
94)]
95pub async fn mirror_remote_profile(&self, user_id: &UserId) -> Result<Removed> {
96 assert!(
97 !self.services.globals.user_is_local(user_id),
98 "mirror remote profile called with a local user"
99 );
100
101 let request = Request { user_id: user_id.to_owned(), field: None };
102 let response = self
103 .services
104 .federation
105 .execute(user_id.server_name(), request)
106 .await?;
107
108 self.mirror_profile(user_id, response).await
109}
110
111#[implement(Service)]
117pub(super) async fn mirror_profile(
118 &self,
119 user_id: &UserId,
120 response: Response,
121) -> Result<Removed> {
122 check_served_profile(&response, self.services.config.profile.max_remote_fields)?;
123
124 let profile_lock = self.mutex.lock(user_id).await;
125 let removed: Removed = self
126 .try_profile_field_names(user_id)
127 .ready_try_filter(|name| response.get(name.as_str()).is_none())
128 .try_collect()
129 .await?;
130
131 let fields: Fields = response
132 .into_iter()
133 .map(|(name, value)| (name.into(), Some(value)))
134 .chain(removed.iter().cloned().map(|name| (name, None)))
135 .collect();
136
137 self.set_profile_keys_locked(&profile_lock, user_id, &fields, Some(Propagation::None))
138 .await?;
139
140 Ok(removed)
141}
142
143fn check_served_profile(response: &Response, max_fields: usize) -> Result {
144 check_field_count(response.iter().count(), max_fields)?;
145
146 response
147 .iter()
148 .try_for_each(|(name, _)| check_profile_key(name))?;
149
150 if serialized_len(&response.data)? > MAX_PROFILE_SIZE {
151 return Err!(Request(ProfileTooLarge("Profile exceeds the maximum size of 64 KiB.")));
152 }
153
154 Ok(())
155}
156
157fn check_field_count(count: usize, maximum: usize) -> Result {
158 if count > maximum {
159 return Err!(Request(ProfileTooLarge("Remote profile exceeds the field-count limit.")));
160 }
161
162 Ok(())
163}