-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathmod.rs
More file actions
346 lines (304 loc) · 9.61 KB
/
mod.rs
File metadata and controls
346 lines (304 loc) · 9.61 KB
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
pub mod oidc_server;
pub mod providers;
pub mod sessions;
pub mod user_info;
use std::sync::Arc;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as b64encode};
use futures::{Stream, StreamExt, TryStreamExt};
use reqwest::{
Method,
header::{ACCEPT, CONTENT_TYPE},
};
use ruma::UserId;
use serde::Serialize;
use serde_json::Value as JsonValue;
use tuwunel_core::{
Err, Result, err, implement, info, warn,
utils::{hash::sha256, result::LogErr, stream::ReadyExt},
};
use url::Url;
use self::{oidc_server::OidcServer, providers::Providers, sessions::Sessions};
pub use self::{
oidc_server::ProviderMetadata,
providers::{Provider, ProviderId},
sessions::{CODE_VERIFIER_LENGTH, SESSION_ID_LENGTH, Session, SessionId},
user_info::UserInfo,
};
use crate::SelfServices;
pub struct Service {
services: SelfServices,
pub providers: Arc<Providers>,
pub sessions: Arc<Sessions>,
/// OIDC server (authorization server) for next-gen Matrix auth.
/// Only initialized when identity providers are configured.
pub oidc_server: Option<Arc<OidcServer>>,
}
impl crate::Service for Service {
fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
let providers = Arc::new(Providers::build(args));
let sessions = Arc::new(Sessions::build(args, providers.clone()));
let oidc_server = if !args.server.config.identity_provider.is_empty()
|| args.server.config.well_known.client.is_some()
{
if args.server.config.identity_provider.is_empty() {
warn!("OIDC server enabled (well_known.client is set) but no identity_provider configured; authorization flow will not work");
}
info!("Initializing OIDC server for next-gen auth (MSC2965)");
Some(Arc::new(OidcServer::build(args)?))
} else {
None
};
Ok(Arc::new(Self {
services: args.services.clone(),
sessions,
providers,
oidc_server,
}))
}
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
}
/// Remove all session state for a user. For debug and developer use only;
/// deleting state can cause registration conflicts and unintended
/// re-registrations.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip(self))]
pub async fn delete_user_sessions(&self, user_id: &UserId) {
self.user_sessions(user_id)
.ready_filter_map(Result::ok)
.ready_filter_map(|(_, session)| session.sess_id)
.for_each(async |sess_id| {
self.sessions.delete(&sess_id).await;
})
.await;
}
/// Revoke all session tokens for a user.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip(self))]
pub async fn revoke_user_tokens(&self, user_id: &UserId) {
self.user_sessions(user_id)
.ready_filter_map(Result::ok)
.for_each(async |(provider, session)| {
self.revoke_token((&provider, &session))
.await
.log_err()
.ok();
})
.await;
}
/// Get user's authorizations. Lists pairs of `(Provider, Session)` for a user.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip(self))]
pub fn user_sessions(
&self,
user_id: &UserId,
) -> impl Stream<Item = Result<(Provider, Session)>> + Send {
self.sessions
.get_by_user(user_id)
.and_then(async |session| Ok((self.sessions.provider(&session).await?, session)))
}
/// Network request to a Provider returning userinfo for a Session. The session
/// must have a valid access token.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip_all, ret)]
pub async fn request_userinfo(
&self,
(provider, session): (&Provider, &Session),
) -> Result<UserInfo> {
#[derive(Debug, Serialize)]
struct Query;
let url = provider
.userinfo_url
.clone()
.ok_or_else(|| err!(Config("userinfo_url", "Missing userinfo URL in config")))?;
self.request((Some(provider), Some(session)), Method::GET, url, Option::<Query>::None)
.await
.and_then(|value| serde_json::from_value(value).map_err(Into::into))
.log_err()
}
/// Network request to a Provider returning information for a Session based on
/// its access token.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip_all, ret)]
pub async fn request_tokeninfo(
&self,
(provider, session): (&Provider, &Session),
) -> Result<UserInfo> {
#[derive(Debug, Serialize)]
struct Query;
let url = provider
.introspection_url
.clone()
.ok_or_else(|| {
err!(Config("introspection_url", "Missing introspection URL in config"))
})?;
self.request((Some(provider), Some(session)), Method::GET, url, Option::<Query>::None)
.await
.and_then(|value| serde_json::from_value(value).map_err(Into::into))
.log_err()
}
/// Network request to a Provider revoking a Session's token.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip_all, ret)]
pub async fn revoke_token(&self, (provider, session): (&Provider, &Session)) -> Result {
#[derive(Debug, Serialize)]
struct RevokeQuery<'a> {
client_id: &'a str,
client_secret: &'a str,
}
let client_secret = provider.get_client_secret().await?;
let query = RevokeQuery {
client_id: &provider.client_id,
client_secret: &client_secret,
};
let url = provider
.revocation_url
.clone()
.ok_or_else(|| err!(Config("revocation_url", "Missing revocation URL in config")))?;
self.request((Some(provider), Some(session)), Method::POST, url, Some(query))
.await
.log_err()
.map(|_| ())
}
/// Network request to a Provider to obtain an access token for a Session using
/// a provided code.
#[implement(Service)]
#[tracing::instrument(level = "debug", skip_all, ret)]
pub async fn request_token(
&self,
(provider, session): (&Provider, &Session),
code: &str,
) -> Result<Session> {
#[derive(Debug, Serialize)]
struct TokenQuery<'a> {
client_id: &'a str,
client_secret: &'a str,
grant_type: &'a str,
code: &'a str,
code_verifier: Option<&'a str>,
redirect_uri: Option<&'a str>,
}
let client_secret = provider.get_client_secret().await?;
let query = TokenQuery {
client_id: &provider.client_id,
client_secret: &client_secret,
grant_type: "authorization_code",
code,
code_verifier: session.code_verifier.as_deref(),
redirect_uri: provider.callback_url.as_ref().map(Url::as_str),
};
let url = provider
.token_url
.clone()
.ok_or_else(|| err!(Config("token_url", "Missing token URL in config")))?;
self.request((Some(provider), Some(session)), Method::POST, url, Some(query))
.await
.and_then(|value| serde_json::from_value(value).map_err(Into::into))
.log_err()
}
/// Send a request to a provider; this is somewhat abstract since URL's are
/// formed prior to this call and could point at anything, however this function
/// uses the oauth-specific http client and is configured for JSON with special
/// casing for an `error` property in the response.
#[implement(Service)]
#[tracing::instrument(
name = "request",
level = "debug",
ret(level = "trace"),
skip(self, body)
)]
pub async fn request<Body>(
&self,
(provider, session): (Option<&Provider>, Option<&Session>),
method: Method,
url: Url,
body: Option<Body>,
) -> Result<JsonValue>
where
Body: Serialize,
{
let mut request = self
.services
.client
.oauth
.request(method, url)
.header(ACCEPT, "application/json");
if let Some(body) = body.map(serde_html_form::to_string).transpose()? {
request = request
.header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(body);
}
if let Some(session) = session
&& let Some(access_token) = session.access_token.clone()
{
request = request.bearer_auth(access_token);
}
let response: JsonValue = request
.send()
.await?
.error_for_status()?
.json()
.await?;
if let Some(response) = response.as_object().as_ref()
&& let Some(error) = response.get("error").and_then(JsonValue::as_str)
{
let description = response
.get("error_description")
.and_then(JsonValue::as_str)
.unwrap_or("(no description)");
return Err!(Request(Forbidden("Error from provider: {error}: {description}",)));
}
Ok(response)
}
/// Generate a unique-id string determined by the combination of `Provider` and
/// `Session` instances.
#[inline]
pub fn unique_id((provider, session): (&Provider, &Session)) -> Result<String> {
unique_id_parts((provider, session)).and_then(unique_id_iss_sub)
}
/// Generate a unique-id string determined by the combination of `Provider`
/// instance and `sub` string.
#[inline]
pub fn unique_id_sub((provider, sub): (&Provider, &str)) -> Result<String> {
unique_id_sub_parts((provider, sub)).and_then(unique_id_iss_sub)
}
/// Generate a unique-id string determined by the combination of `issuer_url`
/// and `Session` instance.
#[inline]
pub fn unique_id_iss((iss, session): (&str, &Session)) -> Result<String> {
unique_id_iss_parts((iss, session)).and_then(unique_id_iss_sub)
}
/// Generate a unique-id string determined by the `issuer_url` and the `sub`
/// strings directly.
pub fn unique_id_iss_sub((iss, sub): (&str, &str)) -> Result<String> {
let hash = sha256::delimited([iss, sub].iter());
let b64 = b64encode.encode(hash);
Ok(b64)
}
fn unique_id_parts<'a>(
(provider, session): (&'a Provider, &'a Session),
) -> Result<(&'a str, &'a str)> {
provider
.issuer_url
.as_ref()
.map(Url::as_str)
.ok_or_else(|| err!(Config("issuer_url", "issuer_url not found for this provider.")))
.and_then(|iss| unique_id_iss_parts((iss, session)))
}
fn unique_id_sub_parts<'a>(
(provider, sub): (&'a Provider, &'a str),
) -> Result<(&'a str, &'a str)> {
provider
.issuer_url
.as_ref()
.map(Url::as_str)
.ok_or_else(|| err!(Config("issuer_url", "issuer_url not found for this provider.")))
.map(|iss| (iss, sub))
}
fn unique_id_iss_parts<'a>((iss, session): (&'a str, &'a Session)) -> Result<(&'a str, &'a str)> {
session
.user_info
.as_ref()
.map(|user_info| user_info.sub.as_str())
.ok_or_else(|| err!(Request(NotFound("user_info not found for this session."))))
.map(|sub| (iss, sub))
}