1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use std::{
collections::{HashMap, HashSet},
convert::TryFrom,
};
use anyhow::{anyhow, Context, Error};
use async_trait::async_trait;
use data_encoding::HEXLOWER;
use hmac::{Hmac, Mac};
use log::debug;
use matrix_sdk::{
ruma::{
api::{
client::{error::ErrorKind, Error as ClientError},
error::{FromHttpResponseError, ServerError},
},
RoomAliasId,
},
ClientConfig, HttpError,
};
use rand::Rng;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use sha1::Sha1;
use typed_builder::TypedBuilder;
type HmacSha1 = Hmac<Sha1>;
const RETRY_ATTEMPTS: u64 = 10;
const TIMEOUT_SEC: u64 = 15;
#[derive(Clone, Debug, Deserialize)]
pub enum RateLimit {
#[serde(alias = "default")]
Default,
#[serde(alias = "unlimited")]
Unlimited,
}
impl Default for RateLimit {
fn default() -> Self {
RateLimit::Default
}
}
#[derive(Clone, TypedBuilder, Debug, Deserialize)]
pub struct User {
#[serde(default)]
#[builder(default = false)]
pub admin: bool,
pub localname: String,
#[serde(default = "User::default_password")]
#[builder(default = User::default_password())]
pub password: String,
#[serde(default)]
#[builder(default)]
pub rooms: Vec<Room>,
#[serde(default)]
#[builder(default)]
pub rate_limit: RateLimit,
}
impl User {
fn default_password() -> String {
"password".to_string()
}
}
#[derive(Clone, TypedBuilder, Debug, Deserialize)]
pub struct Room {
#[serde(default)]
#[builder(default = false)]
pub public: bool,
#[serde(default)]
#[builder(default)]
pub members: Vec<String>,
#[serde(default)]
#[builder(default)]
pub name: Option<String>,
#[serde(default)]
#[builder(default)]
pub alias: Option<String>,
#[serde(default)]
#[builder(default)]
pub topic: Option<String>,
}
#[async_trait]
trait Retry {
async fn auto_retry(&self, attempts: u64) -> Result<reqwest::Response, Error>;
}
#[async_trait]
impl Retry for reqwest::RequestBuilder {
async fn auto_retry(&self, max_attempts: u64) -> Result<reqwest::Response, Error> {
const BASE_INTERVAL_MS: std::ops::Range<u64> = 300..1000;
let mut attempt = 1;
loop {
match self
.try_clone()
.expect("Cannot auto-retry non-clonable requests")
.send()
.await
{
Ok(response) => {
debug!("auto_retry success");
break Ok(response);
}
Err(err) => {
debug!("auto_retry error {:?} => {:?}", err, err.status());
let should_retry = attempt < max_attempts
&& (err.is_connect() || err.is_timeout() || err.is_request());
if should_retry {
let duration =
(attempt * attempt) * rand::thread_rng().gen_range(BASE_INTERVAL_MS);
attempt += 1;
debug!("auto_retry: sleeping {}ms", duration);
tokio::time::sleep(std::time::Duration::from_millis(duration)).await;
} else {
debug!("auto_retry: giving up!");
return Err(err.into());
}
}
}
}
}
}
async fn register_user(
base_url: &str,
registration_shared_secret: &str,
user: &User,
) -> Result<(), Error> {
#[derive(Debug, Deserialize)]
struct GetRegisterResponse {
nonce: String,
}
let registration_url = format!("{}/_synapse/admin/v1/register", base_url);
debug!(
"Registration shared secret: {}, url: {}, user: {:#?}",
registration_shared_secret, registration_url, user
);
let client = reqwest::Client::new();
let nonce = client
.get(®istration_url)
.auto_retry(RETRY_ATTEMPTS)
.await?
.json::<GetRegisterResponse>()
.await?
.nonce;
let mut mac =
HmacSha1::new_from_slice(registration_shared_secret.as_bytes()).map_err(|err| {
anyhow!(
"Couldn't use the provided registration shared secret to create a hmac: {}",
err
)
})?;
mac.update(
format!(
"{nonce}\0{username}\0{password}\0{admin}",
nonce = nonce,
username = user.localname,
password = user.password,
admin = if user.admin { "admin" } else { "notadmin" }
)
.as_bytes(),
);
#[derive(Debug, Serialize)]
struct RegistrationPayload {
nonce: String,
username: String,
displayname: String,
password: String,
admin: bool,
mac: String,
}
let registration_payload = RegistrationPayload {
nonce,
username: user.localname.to_string(),
displayname: user.localname.to_string(),
password: user.password.to_string(),
admin: user.admin,
mac: HEXLOWER.encode(&mac.finalize().into_bytes()),
};
debug!(
"Sending payload {:#?}",
serde_json::to_string_pretty(®istration_payload)
);
#[derive(Debug, Deserialize)]
struct ErrorResponse {
errcode: String,
error: String,
}
let client = reqwest::Client::new();
let response = client
.post(®istration_url)
.json(®istration_payload)
.auto_retry(RETRY_ATTEMPTS)
.await?;
match response.status() {
StatusCode::OK => Ok(()),
_ => {
let body = response.json::<ErrorResponse>().await?;
Err(anyhow!(
"Homeserver responded with errcode: {}, error: {}",
body.errcode,
body.error
))
}
}
}
async fn ensure_user_exists(
base_url: &str,
registration_shared_secret: &str,
user: &User,
) -> Result<matrix_sdk::Client, Error> {
debug!(
"ensure_user_exists at {}: user {} with password {}",
base_url, user.localname, user.password
);
use matrix_sdk::ruma::api::client::error::*;
use matrix_sdk::ruma::api::error::*;
let homeserver_url = reqwest::Url::parse(base_url)?;
let config = ClientConfig::new();
config
.get_request_config()
.retry_limit(RETRY_ATTEMPTS)
.retry_timeout(std::time::Duration::new(TIMEOUT_SEC, 0));
let client = matrix_sdk::Client::new_with_config(homeserver_url, config)?;
match client
.login(&user.localname, &user.password, None, None)
.await
{
Err(matrix_sdk::Error::Http(matrix_sdk::HttpError::ClientApi(
FromHttpResponseError::Http(ServerError::Known(err)),
))) if err.kind == ErrorKind::Forbidden => {
debug!("Could not authenticate {}", err);
}
Ok(_) => return Ok(client),
Err(err) => return Err(err).context("Error attempting to login"),
}
register_user(base_url, registration_shared_secret, user).await?;
client
.login(&user.localname, &user.password, None, None)
.await?;
Ok(client)
}
pub async fn handle_user_registration(config: &crate::Config) -> Result<(), Error> {
let admin = ensure_user_exists(
&config.homeserver.public_baseurl,
&config.homeserver.registration_shared_secret,
&User::builder()
.admin(true)
.localname("mx-tester-admin".to_string())
.build(),
)
.await?;
let mut clients = HashMap::new();
for user in &config.users {
let client = ensure_user_exists(
&config.homeserver.public_baseurl,
&config.homeserver.registration_shared_secret,
user,
)
.await
.with_context(|| format!("Could not setup user {}", user.localname))?;
if let RateLimit::Unlimited = user.rate_limit {
use override_rate_limits::*;
let user_id = client
.user_id()
.await
.expect("Client doesn't have a user id");
let request = Request::new(&user_id, Some(0), Some(0));
let _ = admin.send(request, None).await?;
}
clients.insert(user.localname.clone(), client);
}
let mut aliases = HashSet::new();
for user in &config.users {
if user.rooms.is_empty() {
continue;
}
let client = clients.get(&user.localname).unwrap();
let my_user_id = client.user_id().await.ok_or_else(|| {
anyhow!(
"Cannot determine full user id for own user {}.",
user.localname
)
})?;
for room in &user.rooms {
let mut request = matrix_sdk::ruma::api::client::r0::room::create_room::Request::new();
if room.public {
request.preset = Some(
matrix_sdk::ruma::api::client::r0::room::create_room::RoomPreset::PublicChat,
);
} else {
request.preset = Some(
matrix_sdk::ruma::api::client::r0::room::create_room::RoomPreset::PrivateChat,
);
}
if let Some(ref name) = room.name {
request.name = Some(TryFrom::<&str>::try_from(name.as_str())?);
}
if let Some(ref alias) = room.alias {
if !aliases.insert(alias) {
return Err(anyhow!(
"Attempting to create more than one room with alias {}",
alias
));
}
request.room_alias_name = Some(alias.as_ref());
let full_alias = format!("#{}:{}", alias, config.homeserver.server_name);
debug!("Attempting to register alias {}, this may require unregistering previous instances first.", full_alias);
let room_alias_id = RoomAliasId::try_from(full_alias.as_ref())?;
match client
.send(
matrix_sdk::ruma::api::client::r0::alias::delete_alias::Request::new(
&room_alias_id,
),
None,
)
.await
{
Ok(_) => Ok(()),
Err(HttpError::Server(ref code)) if code.as_u16() == 404 => Ok(()),
Err(HttpError::ClientApi(FromHttpResponseError::Http(ServerError::Known(
ClientError {
kind: ErrorKind::NotFound,
..
},
)))) => Ok(()),
Err(err) => Err(err),
}
.context("Error while attempting to unregister existing alias")?;
}
if let Some(ref topic) = room.topic {
request.topic = Some(topic.as_ref());
}
let mut invites = vec![];
for member in &room.members {
let member_client = clients.get(member).ok_or_else(|| {
anyhow!(
"Cannot invite user {}: we haven't created this user.",
member
)
})?;
let user_id = member_client
.user_id()
.await
.ok_or_else(|| anyhow!("Cannot determine full user id for user {}.", member))?;
if my_user_id == user_id {
continue;
}
invites.push(user_id);
}
request.invite = &invites;
let room_id = client.create_room(request).await?.room_id;
for member in &room.members {
let member_client = clients.get(member).unwrap();
member_client.join_room_by_id(&room_id).await?;
}
}
}
Ok(())
}
mod override_rate_limits {
use matrix_sdk::ruma::api::ruma_api;
use matrix_sdk::ruma::UserId;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata: {
description: "Override rate limits",
method: POST,
name: "override_rate_limit",
path: "/_synapse/admin/v1/users/:user_id/override_ratelimit",
rate_limited: false,
authentication: AccessToken,
}
request: {
#[ruma_api(path)]
pub user_id: &'a UserId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub messages_per_second: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub burst_count: Option<u32>
}
response: {
#[ruma_api(body)]
pub limits: UserLimits,
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct UserLimits {
pub messages_per_second: u32,
pub burst_count: u32,
}
impl<'a> Request<'a> {
pub fn new(
user_id: &'a UserId,
messages_per_second: Option<u32>,
burst_count: Option<u32>,
) -> Self {
Self {
user_id,
messages_per_second,
burst_count,
}
}
}
impl Response {
#[allow(dead_code)]
pub fn new(limits: UserLimits) -> Self {
Self { limits }
}
}
}