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
use anyhow::{anyhow, Error};
use data_encoding::HEXLOWER;
use hmac::{Hmac, Mac, NewMac};
use log::debug;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use sha1::Sha1;
type HmacSha1 = Hmac<Sha1>;
#[derive(Debug, Deserialize)]
pub struct User {
#[serde(default)]
pub admin: bool,
pub localname: String,
#[serde(default)]
password: Option<String>,
}
impl User {
pub fn password(&self) -> &str {
match &self.password {
Some(password) => password,
None => &self.localname,
}
}
}
pub 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 nonce = reqwest::get(®istration_url)
.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)
.send()
.await?;
match response.status() {
StatusCode::OK => Ok(()),
_ => {
let body = response.json::<ErrorResponse>().await?;
Err(anyhow!(
"Homeserver responded with errcode: {}, error: {}",
body.errcode,
body.error
))
}
}
}
pub async fn login(base_url: &str, user: &User) -> Result<(), Error> {
#[derive(Debug, Serialize)]
struct Identifier {
#[serde(rename(serialize = "type"))]
identifier_type: String,
user: String,
}
#[derive(Debug, Serialize)]
struct LoginPayload {
#[serde(rename(serialize = "type"))]
login_type: String,
identifier: Identifier,
password: String,
}
let login_payload = LoginPayload {
login_type: "m.login.password".to_string(),
password: user.password().to_string(),
identifier: Identifier {
identifier_type: "m.id.user".to_string(),
user: user.localname.to_string(),
},
};
let login_url = format!("{base_url}/_matrix/client/r0/login", base_url = base_url);
reqwest::Client::new()
.post(login_url)
.json(&login_payload)
.send()
.await?;
Ok(())
}
pub async fn ensure_user_exists(
base_url: &str,
registration_shared_secret: &str,
user: &User,
) -> Result<(), Error> {
match login(base_url, user).await {
Ok(response) => Ok(response),
Err(_) => {
debug!("Registering user {}", user.localname);
Ok(register_user(base_url, registration_shared_secret, user).await?)
}
}
}