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::CompatRefresh::route(),
285            post(self::compat::refresh::post),
286        )
287        .route(
288            mas_router::CompatLoginSsoRedirect::route(),
289            get(self::compat::login_sso_redirect::get),
290        )
291        .route(
292            mas_router::CompatLoginSsoRedirectIdp::route(),
293            get(self::compat::login_sso_redirect::get),
294        )
295        .route(
296            mas_router::CompatLoginSsoRedirectSlash::route(),
297            get(self::compat::login_sso_redirect::get),
298        )
299        .layer(
300            CorsLayer::new()
301                .allow_origin(Any)
302                .allow_methods(Any)
303                .allow_otel_headers([
304                    AUTHORIZATION,
305                    ACCEPT,
306                    ACCEPT_LANGUAGE,
307                    CONTENT_LANGUAGE,
308                    CONTENT_TYPE,
309                    HeaderName::from_static("x-requested-with"),
310                ])
311                .max_age(Duration::from_secs(60 * 60)),
312        )
313}
314
315#[allow(clippy::too_many_lines)]
316pub fn human_router<S>(templates: Templates) -> Router<S>
317where
318    S: Clone + Send + Sync + 'static,
319    UrlBuilder: FromRef<S>,
320    PreferredLanguage: FromRequestParts<S>,
321    BoxRepository: FromRequestParts<S>,
322    CookieJar: FromRequestParts<S>,
323    BoundActivityTracker: FromRequestParts<S>,
324    RequesterFingerprint: FromRequestParts<S>,
325    Encrypter: FromRef<S>,
326    Templates: FromRef<S>,
327    Keystore: FromRef<S>,
328    PasswordManager: FromRef<S>,
329    MetadataCache: FromRef<S>,
330    SiteConfig: FromRef<S>,
331    Limiter: FromRef<S>,
332    reqwest::Client: FromRef<S>,
333    Arc<dyn HomeserverConnection>: FromRef<S>,
334    BoxClock: FromRequestParts<S>,
335    BoxRng: FromRequestParts<S>,
336    Policy: FromRequestParts<S>,
337{
338    Router::new()
339        // XXX: hard-coded redirect from /account to /account/
340        .route(
341            "/account",
342            get(
343                async |State(url_builder): State<UrlBuilder>, RawQuery(query): RawQuery| {
344                    let prefix = url_builder.prefix().unwrap_or_default();
345                    let route = mas_router::Account::route();
346                    let destination = if let Some(query) = query {
347                        format!("{prefix}{route}?{query}")
348                    } else {
349                        format!("{prefix}{route}")
350                    };
351
352                    axum::response::Redirect::to(&destination)
353                },
354            ),
355        )
356        .route(mas_router::Account::route(), get(self::views::app::get))
357        .route(
358            mas_router::AccountWildcard::route(),
359            get(self::views::app::get),
360        )
361        .route(
362            mas_router::AccountRecoveryFinish::route(),
363            get(self::views::app::get_anonymous),
364        )
365        .route(
366            mas_router::ChangePasswordDiscovery::route(),
367            get(async |State(url_builder): State<UrlBuilder>| {
368                url_builder.redirect(&mas_router::AccountPasswordChange)
369            }),
370        )
371        .route(mas_router::Index::route(), get(self::views::index::get))
372        .route(
373            mas_router::Login::route(),
374            get(self::views::login::get).post(self::views::login::post),
375        )
376        .route(mas_router::Logout::route(), post(self::views::logout::post))
377        .route(
378            mas_router::Register::route(),
379            get(self::views::register::get),
380        )
381        .route(
382            mas_router::PasswordRegister::route(),
383            get(self::views::register::password::get).post(self::views::register::password::post),
384        )
385        .route(
386            mas_router::RegisterVerifyEmail::route(),
387            get(self::views::register::steps::verify_email::get)
388                .post(self::views::register::steps::verify_email::post),
389        )
390        .route(
391            mas_router::RegisterDisplayName::route(),
392            get(self::views::register::steps::display_name::get)
393                .post(self::views::register::steps::display_name::post),
394        )
395        .route(
396            mas_router::RegisterFinish::route(),
397            get(self::views::register::steps::finish::get),
398        )
399        .route(
400            mas_router::AccountRecoveryStart::route(),
401            get(self::views::recovery::start::get).post(self::views::recovery::start::post),
402        )
403        .route(
404            mas_router::AccountRecoveryProgress::route(),
405            get(self::views::recovery::progress::get).post(self::views::recovery::progress::post),
406        )
407        .route(
408            mas_router::OAuth2AuthorizationEndpoint::route(),
409            get(self::oauth2::authorization::get),
410        )
411        .route(
412            mas_router::Consent::route(),
413            get(self::oauth2::authorization::consent::get)
414                .post(self::oauth2::authorization::consent::post),
415        )
416        .route(
417            mas_router::CompatLoginSsoComplete::route(),
418            get(self::compat::login_sso_complete::get).post(self::compat::login_sso_complete::post),
419        )
420        .route(
421            mas_router::UpstreamOAuth2Authorize::route(),
422            get(self::upstream_oauth2::authorize::get),
423        )
424        .route(
425            mas_router::UpstreamOAuth2Callback::route(),
426            get(self::upstream_oauth2::callback::handler)
427                .post(self::upstream_oauth2::callback::handler),
428        )
429        .route(
430            mas_router::UpstreamOAuth2Link::route(),
431            get(self::upstream_oauth2::link::get).post(self::upstream_oauth2::link::post),
432        )
433        .route(
434            mas_router::DeviceCodeLink::route(),
435            get(self::oauth2::device::link::get),
436        )
437        .route(
438            mas_router::DeviceCodeConsent::route(),
439            get(self::oauth2::device::consent::get).post(self::oauth2::device::consent::post),
440        )
441        .layer(AndThenLayer::new(
442            async move |response: axum::response::Response| {
443                // Error responses should have an ErrorContext attached to them
444                let ext = response.extensions().get::<ErrorContext>();
445                if let Some(ctx) = ext {
446                    if let Ok(res) = templates.render_error(ctx) {
447                        let (mut parts, _original_body) = response.into_parts();
448                        parts.headers.remove(CONTENT_TYPE);
449                        parts.headers.remove(CONTENT_LENGTH);
450                        return Ok((parts, Html(res)).into_response());
451                    }
452                }
453
454                Ok::<_, Infallible>(response)
455            },
456        ))
457}
458
459/// The fallback handler for all routes that don't match anything else.
460///
461/// # Errors
462///
463/// Returns an error if the template rendering fails.
464pub async fn fallback(
465    State(templates): State<Templates>,
466    OriginalUri(uri): OriginalUri,
467    method: Method,
468    version: Version,
469    PreferredLanguage(locale): PreferredLanguage,
470) -> Result<impl IntoResponse, InternalError> {
471    let ctx = NotFoundContext::new(&method, version, &uri).with_language(locale);
472    // XXX: this should look at the Accept header and return JSON if requested
473
474    let res = templates.render_not_found(&ctx)?;
475
476    Ok((StatusCode::NOT_FOUND, Html(res)))
477}