mas_handlers/
lib.rs

1// Copyright 2024, 2025 New Vector Ltd.
2// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE in the repository root for full details.
6
7#![deny(clippy::future_not_send)]
8#![allow(
9    // Some axum handlers need that
10    clippy::unused_async,
11    // Because of how axum handlers work, we sometime have take many arguments
12    clippy::too_many_arguments,
13    // Code generated by tracing::instrument trigger this when returning an `impl Trait`
14    // See https://github.com/tokio-rs/tracing/issues/2613
15    clippy::let_with_type_underscore,
16)]
17
18use std::{
19    convert::Infallible,
20    sync::{Arc, LazyLock},
21    time::Duration,
22};
23
24use axum::{
25    Extension, Router,
26    extract::{FromRef, FromRequestParts, OriginalUri, RawQuery, State},
27    http::Method,
28    response::{Html, IntoResponse},
29    routing::{get, post},
30};
31use headers::HeaderName;
32use hyper::{
33    StatusCode, Version,
34    header::{
35        ACCEPT, ACCEPT_LANGUAGE, AUTHORIZATION, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_TYPE,
36    },
37};
38use mas_axum_utils::{InternalError, cookies::CookieJar};
39use mas_data_model::SiteConfig;
40use mas_http::CorsLayerExt;
41use mas_keystore::{Encrypter, Keystore};
42use mas_matrix::HomeserverConnection;
43use mas_policy::Policy;
44use mas_router::{Route, UrlBuilder};
45use mas_storage::{BoxClock, BoxRepository, BoxRng};
46use mas_templates::{ErrorContext, NotFoundContext, TemplateContext, Templates};
47use opentelemetry::metrics::Meter;
48use sqlx::PgPool;
49use tower::util::AndThenLayer;
50use tower_http::cors::{Any, CorsLayer};
51
52use self::{graphql::ExtraRouterParameters, passwords::PasswordManager};
53
54mod admin;
55mod compat;
56mod graphql;
57mod health;
58mod oauth2;
59pub mod passwords;
60pub mod upstream_oauth2;
61mod views;
62
63mod activity_tracker;
64mod captcha;
65mod preferred_language;
66mod rate_limit;
67mod session;
68#[cfg(test)]
69mod test_utils;
70
71static METER: LazyLock<Meter> = LazyLock::new(|| {
72    let scope = opentelemetry::InstrumentationScope::builder(env!("CARGO_PKG_NAME"))
73        .with_version(env!("CARGO_PKG_VERSION"))
74        .with_schema_url(opentelemetry_semantic_conventions::SCHEMA_URL)
75        .build();
76
77    opentelemetry::global::meter_with_scope(scope)
78});
79
80/// Implement `From<E>` for `RouteError`, for "internal server error" kind of
81/// errors.
82#[macro_export]
83macro_rules! impl_from_error_for_route {
84    ($route_error:ty : $error:ty) => {
85        impl From<$error> for $route_error {
86            fn from(e: $error) -> Self {
87                Self::Internal(Box::new(e))
88            }
89        }
90    };
91    ($error:ty) => {
92        impl_from_error_for_route!(self::RouteError: $error);
93    };
94}
95
96pub use mas_axum_utils::{ErrorWrapper, cookies::CookieManager};
97
98pub use self::{
99    activity_tracker::{ActivityTracker, Bound as BoundActivityTracker},
100    admin::router as admin_api_router,
101    graphql::{
102        Schema as GraphQLSchema, schema as graphql_schema, schema_builder as graphql_schema_builder,
103    },
104    preferred_language::PreferredLanguage,
105    rate_limit::{Limiter, RequesterFingerprint},
106    upstream_oauth2::cache::MetadataCache,
107};
108
109pub fn healthcheck_router<S>() -> Router<S>
110where
111    S: Clone + Send + Sync + 'static,
112    PgPool: FromRef<S>,
113{
114    Router::new().route(mas_router::Healthcheck::route(), get(self::health::get))
115}
116
117pub fn graphql_router<S>(playground: bool, undocumented_oauth2_access: bool) -> Router<S>
118where
119    S: Clone + Send + Sync + 'static,
120    graphql::Schema: FromRef<S>,
121    BoundActivityTracker: FromRequestParts<S>,
122    BoxRepository: FromRequestParts<S>,
123    BoxClock: FromRequestParts<S>,
124    Encrypter: FromRef<S>,
125    CookieJar: FromRequestParts<S>,
126    Limiter: FromRef<S>,
127    RequesterFingerprint: FromRequestParts<S>,
128{
129    let mut router = Router::new()
130        .route(
131            mas_router::GraphQL::route(),
132            get(self::graphql::get).post(self::graphql::post),
133        )
134        // Pass the undocumented_oauth2_access parameter through the request extension, as it is
135        // per-listener
136        .layer(Extension(ExtraRouterParameters {
137            undocumented_oauth2_access,
138        }))
139        .layer(
140            CorsLayer::new()
141                .allow_origin(Any)
142                .allow_methods(Any)
143                .allow_otel_headers([
144                    AUTHORIZATION,
145                    ACCEPT,
146                    ACCEPT_LANGUAGE,
147                    CONTENT_LANGUAGE,
148                    CONTENT_TYPE,
149                ]),
150        );
151
152    if playground {
153        router = router.route(
154            mas_router::GraphQLPlayground::route(),
155            get(self::graphql::playground),
156        );
157    }
158
159    router
160}
161
162pub fn discovery_router<S>() -> Router<S>
163where
164    S: Clone + Send + Sync + 'static,
165    Keystore: FromRef<S>,
166    SiteConfig: FromRef<S>,
167    UrlBuilder: FromRef<S>,
168    BoxClock: FromRequestParts<S>,
169    BoxRng: FromRequestParts<S>,
170{
171    Router::new()
172        .route(
173            mas_router::OidcConfiguration::route(),
174            get(self::oauth2::discovery::get),
175        )
176        .route(
177            mas_router::Webfinger::route(),
178            get(self::oauth2::webfinger::get),
179        )
180        .layer(
181            CorsLayer::new()
182                .allow_origin(Any)
183                .allow_methods(Any)
184                .allow_otel_headers([
185                    AUTHORIZATION,
186                    ACCEPT,
187                    ACCEPT_LANGUAGE,
188                    CONTENT_LANGUAGE,
189                    CONTENT_TYPE,
190                ])
191                .max_age(Duration::from_secs(60 * 60)),
192        )
193}
194
195pub fn api_router<S>() -> Router<S>
196where
197    S: Clone + Send + Sync + 'static,
198    Keystore: FromRef<S>,
199    UrlBuilder: FromRef<S>,
200    BoxRepository: FromRequestParts<S>,
201    ActivityTracker: FromRequestParts<S>,
202    BoundActivityTracker: FromRequestParts<S>,
203    Encrypter: FromRef<S>,
204    reqwest::Client: FromRef<S>,
205    SiteConfig: FromRef<S>,
206    Templates: FromRef<S>,
207    Arc<dyn HomeserverConnection>: FromRef<S>,
208    BoxClock: FromRequestParts<S>,
209    BoxRng: FromRequestParts<S>,
210    Policy: FromRequestParts<S>,
211{
212    // All those routes are API-like, with a common CORS layer
213    Router::new()
214        .route(
215            mas_router::OAuth2Keys::route(),
216            get(self::oauth2::keys::get),
217        )
218        .route(
219            mas_router::OidcUserinfo::route(),
220            get(self::oauth2::userinfo::get).post(self::oauth2::userinfo::get),
221        )
222        .route(
223            mas_router::OAuth2Introspection::route(),
224            post(self::oauth2::introspection::post),
225        )
226        .route(
227            mas_router::OAuth2Revocation::route(),
228            post(self::oauth2::revoke::post),
229        )
230        .route(
231            mas_router::OAuth2TokenEndpoint::route(),
232            post(self::oauth2::token::post),
233        )
234        .route(
235            mas_router::OAuth2RegistrationEndpoint::route(),
236            post(self::oauth2::registration::post),
237        )
238        .route(
239            mas_router::OAuth2DeviceAuthorizationEndpoint::route(),
240            post(self::oauth2::device::authorize::post),
241        )
242        .layer(
243            CorsLayer::new()
244                .allow_origin(Any)
245                .allow_methods(Any)
246                .allow_otel_headers([
247                    AUTHORIZATION,
248                    ACCEPT,
249                    ACCEPT_LANGUAGE,
250                    CONTENT_LANGUAGE,
251                    CONTENT_TYPE,
252                    // Swagger will send this header, so we have to allow it to avoid CORS errors
253                    HeaderName::from_static("x-requested-with"),
254                ])
255                .max_age(Duration::from_secs(60 * 60)),
256        )
257}
258
259#[allow(clippy::trait_duplication_in_bounds)]
260pub fn compat_router<S>() -> Router<S>
261where
262    S: Clone + Send + Sync + 'static,
263    UrlBuilder: FromRef<S>,
264    SiteConfig: FromRef<S>,
265    Arc<dyn HomeserverConnection>: FromRef<S>,
266    PasswordManager: FromRef<S>,
267    Limiter: FromRef<S>,
268    BoundActivityTracker: FromRequestParts<S>,
269    RequesterFingerprint: FromRequestParts<S>,
270    BoxRepository: FromRequestParts<S>,
271    BoxClock: FromRequestParts<S>,
272    BoxRng: FromRequestParts<S>,
273{
274    Router::new()
275        .route(
276            mas_router::CompatLogin::route(),
277            get(self::compat::login::get).post(self::compat::login::post),
278        )
279        .route(
280            mas_router::CompatLogout::route(),
281            post(self::compat::logout::post),
282        )
283        .route(
284            mas_router::CompatLogoutAll::route(),
285            post(self::compat::logout_all::post),
286        )
287        .route(
288            mas_router::CompatRefresh::route(),
289            post(self::compat::refresh::post),
290        )
291        .route(
292            mas_router::CompatLoginSsoRedirect::route(),
293            get(self::compat::login_sso_redirect::get),
294        )
295        .route(
296            mas_router::CompatLoginSsoRedirectIdp::route(),
297            get(self::compat::login_sso_redirect::get),
298        )
299        .route(
300            mas_router::CompatLoginSsoRedirectSlash::route(),
301            get(self::compat::login_sso_redirect::get),
302        )
303        .layer(
304            CorsLayer::new()
305                .allow_origin(Any)
306                .allow_methods(Any)
307                .allow_otel_headers([
308                    AUTHORIZATION,
309                    ACCEPT,
310                    ACCEPT_LANGUAGE,
311                    CONTENT_LANGUAGE,
312                    CONTENT_TYPE,
313                    HeaderName::from_static("x-requested-with"),
314                ])
315                .max_age(Duration::from_secs(60 * 60)),
316        )
317}
318
319#[allow(clippy::too_many_lines)]
320pub fn human_router<S>(templates: Templates) -> Router<S>
321where
322    S: Clone + Send + Sync + 'static,
323    UrlBuilder: FromRef<S>,
324    PreferredLanguage: FromRequestParts<S>,
325    BoxRepository: FromRequestParts<S>,
326    CookieJar: FromRequestParts<S>,
327    BoundActivityTracker: FromRequestParts<S>,
328    RequesterFingerprint: FromRequestParts<S>,
329    Encrypter: FromRef<S>,
330    Templates: FromRef<S>,
331    Keystore: FromRef<S>,
332    PasswordManager: FromRef<S>,
333    MetadataCache: FromRef<S>,
334    SiteConfig: FromRef<S>,
335    Limiter: FromRef<S>,
336    reqwest::Client: FromRef<S>,
337    Arc<dyn HomeserverConnection>: FromRef<S>,
338    BoxClock: FromRequestParts<S>,
339    BoxRng: FromRequestParts<S>,
340    Policy: FromRequestParts<S>,
341{
342    Router::new()
343        // XXX: hard-coded redirect from /account to /account/
344        .route(
345            "/account",
346            get(
347                async |State(url_builder): State<UrlBuilder>, RawQuery(query): RawQuery| {
348                    let prefix = url_builder.prefix().unwrap_or_default();
349                    let route = mas_router::Account::route();
350                    let destination = if let Some(query) = query {
351                        format!("{prefix}{route}?{query}")
352                    } else {
353                        format!("{prefix}{route}")
354                    };
355
356                    axum::response::Redirect::to(&destination)
357                },
358            ),
359        )
360        .route(mas_router::Account::route(), get(self::views::app::get))
361        .route(
362            mas_router::AccountWildcard::route(),
363            get(self::views::app::get),
364        )
365        .route(
366            mas_router::AccountRecoveryFinish::route(),
367            get(self::views::app::get_anonymous),
368        )
369        .route(
370            mas_router::ChangePasswordDiscovery::route(),
371            get(async |State(url_builder): State<UrlBuilder>| {
372                url_builder.redirect(&mas_router::AccountPasswordChange)
373            }),
374        )
375        .route(mas_router::Index::route(), get(self::views::index::get))
376        .route(
377            mas_router::Login::route(),
378            get(self::views::login::get).post(self::views::login::post),
379        )
380        .route(mas_router::Logout::route(), post(self::views::logout::post))
381        .route(
382            mas_router::Register::route(),
383            get(self::views::register::get),
384        )
385        .route(
386            mas_router::PasswordRegister::route(),
387            get(self::views::register::password::get).post(self::views::register::password::post),
388        )
389        .route(
390            mas_router::RegisterVerifyEmail::route(),
391            get(self::views::register::steps::verify_email::get)
392                .post(self::views::register::steps::verify_email::post),
393        )
394        .route(
395            mas_router::RegisterDisplayName::route(),
396            get(self::views::register::steps::display_name::get)
397                .post(self::views::register::steps::display_name::post),
398        )
399        .route(
400            mas_router::RegisterFinish::route(),
401            get(self::views::register::steps::finish::get),
402        )
403        .route(
404            mas_router::AccountRecoveryStart::route(),
405            get(self::views::recovery::start::get).post(self::views::recovery::start::post),
406        )
407        .route(
408            mas_router::AccountRecoveryProgress::route(),
409            get(self::views::recovery::progress::get).post(self::views::recovery::progress::post),
410        )
411        .route(
412            mas_router::OAuth2AuthorizationEndpoint::route(),
413            get(self::oauth2::authorization::get),
414        )
415        .route(
416            mas_router::Consent::route(),
417            get(self::oauth2::authorization::consent::get)
418                .post(self::oauth2::authorization::consent::post),
419        )
420        .route(
421            mas_router::CompatLoginSsoComplete::route(),
422            get(self::compat::login_sso_complete::get).post(self::compat::login_sso_complete::post),
423        )
424        .route(
425            mas_router::UpstreamOAuth2Authorize::route(),
426            get(self::upstream_oauth2::authorize::get),
427        )
428        .route(
429            mas_router::UpstreamOAuth2Callback::route(),
430            get(self::upstream_oauth2::callback::handler)
431                .post(self::upstream_oauth2::callback::handler),
432        )
433        .route(
434            mas_router::UpstreamOAuth2Link::route(),
435            get(self::upstream_oauth2::link::get).post(self::upstream_oauth2::link::post),
436        )
437        .route(
438            mas_router::DeviceCodeLink::route(),
439            get(self::oauth2::device::link::get),
440        )
441        .route(
442            mas_router::DeviceCodeConsent::route(),
443            get(self::oauth2::device::consent::get).post(self::oauth2::device::consent::post),
444        )
445        .layer(AndThenLayer::new(
446            async move |response: axum::response::Response| {
447                // Error responses should have an ErrorContext attached to them
448                let ext = response.extensions().get::<ErrorContext>();
449                if let Some(ctx) = ext {
450                    if let Ok(res) = templates.render_error(ctx) {
451                        let (mut parts, _original_body) = response.into_parts();
452                        parts.headers.remove(CONTENT_TYPE);
453                        parts.headers.remove(CONTENT_LENGTH);
454                        return Ok((parts, Html(res)).into_response());
455                    }
456                }
457
458                Ok::<_, Infallible>(response)
459            },
460        ))
461}
462
463/// The fallback handler for all routes that don't match anything else.
464///
465/// # Errors
466///
467/// Returns an error if the template rendering fails.
468pub async fn fallback(
469    State(templates): State<Templates>,
470    OriginalUri(uri): OriginalUri,
471    method: Method,
472    version: Version,
473    PreferredLanguage(locale): PreferredLanguage,
474) -> Result<impl IntoResponse, InternalError> {
475    let ctx = NotFoundContext::new(&method, version, &uri).with_language(locale);
476    // XXX: this should look at the Accept header and return JSON if requested
477
478    let res = templates.render_not_found(&ctx)?;
479
480    Ok((StatusCode::NOT_FOUND, Html(res)))
481}