mas_handlers/admin/
mod.rs

1// Copyright 2024, 2025 New Vector Ltd.
2// Copyright 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
5// Please see LICENSE files in the repository root for full details.
6
7use std::sync::Arc;
8
9use aide::{
10    axum::ApiRouter,
11    openapi::{OAuth2Flow, OAuth2Flows, OpenApi, SecurityScheme, Server, Tag},
12    transform::TransformOpenApi,
13};
14use axum::{
15    Json, Router,
16    extract::{FromRef, FromRequestParts, State},
17    http::HeaderName,
18    response::Html,
19};
20use hyper::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
21use indexmap::IndexMap;
22use mas_axum_utils::InternalError;
23use mas_http::CorsLayerExt;
24use mas_matrix::HomeserverConnection;
25use mas_policy::PolicyFactory;
26use mas_router::{
27    ApiDoc, ApiDocCallback, OAuth2AuthorizationEndpoint, OAuth2TokenEndpoint, Route, SimpleRoute,
28    UrlBuilder,
29};
30use mas_storage::BoxRng;
31use mas_templates::{ApiDocContext, Templates};
32use tower_http::cors::{Any, CorsLayer};
33
34mod call_context;
35mod model;
36mod params;
37mod response;
38mod schema;
39mod v1;
40
41use self::call_context::CallContext;
42use crate::passwords::PasswordManager;
43
44fn finish(t: TransformOpenApi) -> TransformOpenApi {
45    t.title("Matrix Authentication Service admin API")
46        .tag(Tag {
47            name: "compat-session".to_owned(),
48            description: Some("Manage compatibility sessions from legacy clients".to_owned()),
49            ..Tag::default()
50        })
51        .tag(Tag {
52            name: "policy-data".to_owned(),
53            description: Some("Manage the dynamic policy data".to_owned()),
54            ..Tag::default()
55        })
56        .tag(Tag {
57            name: "oauth2-session".to_owned(),
58            description: Some("Manage OAuth2 sessions".to_owned()),
59            ..Tag::default()
60        })
61        .tag(Tag {
62            name: "user".to_owned(),
63            description: Some("Manage users".to_owned()),
64            ..Tag::default()
65        })
66        .tag(Tag {
67            name: "user-email".to_owned(),
68            description: Some("Manage emails associated with users".to_owned()),
69            ..Tag::default()
70        })
71        .tag(Tag {
72            name: "user-session".to_owned(),
73            description: Some("Manage browser sessions of users".to_owned()),
74            ..Tag::default()
75        })
76        .tag(Tag {
77            name: "user-registration-token".to_owned(),
78            description: Some("Manage user registration tokens".to_owned()),
79            ..Tag::default()
80        })
81        .tag(Tag {
82            name: "upstream-oauth-link".to_owned(),
83            description: Some(
84                "Manage links between local users and identities from upstream OAuth 2.0 providers"
85                    .to_owned(),
86            ),
87            ..Default::default()
88        })
89        .security_scheme("oauth2", oauth_security_scheme(None))
90        .security_scheme(
91            "token",
92            SecurityScheme::Http {
93                scheme: "bearer".to_owned(),
94                bearer_format: None,
95                description: Some("An access token with access to the admin API".to_owned()),
96                extensions: IndexMap::default(),
97            },
98        )
99        .security_requirement_scopes("oauth2", ["urn:mas:admin"])
100        .security_requirement_scopes("bearer", ["urn:mas:admin"])
101}
102
103fn oauth_security_scheme(url_builder: Option<&UrlBuilder>) -> SecurityScheme {
104    let (authorization_url, token_url) = if let Some(url_builder) = url_builder {
105        (
106            url_builder.oauth_authorization_endpoint().to_string(),
107            url_builder.oauth_token_endpoint().to_string(),
108        )
109    } else {
110        // This is a dirty fix for Swagger UI: when it joins the URLs with the
111        // base URL, if the path starts with a slash, it will go to the root of
112        // the domain instead of the API root.
113        // It works if we make it explicitly relative
114        (
115            format!(".{}", OAuth2AuthorizationEndpoint::PATH),
116            format!(".{}", OAuth2TokenEndpoint::PATH),
117        )
118    };
119
120    let scopes = IndexMap::from([(
121        "urn:mas:admin".to_owned(),
122        "Grant access to the admin API".to_owned(),
123    )]);
124
125    SecurityScheme::OAuth2 {
126        flows: OAuth2Flows {
127            client_credentials: Some(OAuth2Flow::ClientCredentials {
128                refresh_url: Some(token_url.clone()),
129                token_url: token_url.clone(),
130                scopes: scopes.clone(),
131            }),
132            authorization_code: Some(OAuth2Flow::AuthorizationCode {
133                authorization_url,
134                refresh_url: Some(token_url.clone()),
135                token_url,
136                scopes,
137            }),
138            implicit: None,
139            password: None,
140        },
141        description: None,
142        extensions: IndexMap::default(),
143    }
144}
145
146pub fn router<S>() -> (OpenApi, Router<S>)
147where
148    S: Clone + Send + Sync + 'static,
149    Arc<dyn HomeserverConnection>: FromRef<S>,
150    PasswordManager: FromRef<S>,
151    BoxRng: FromRequestParts<S>,
152    CallContext: FromRequestParts<S>,
153    Templates: FromRef<S>,
154    UrlBuilder: FromRef<S>,
155    Arc<PolicyFactory>: FromRef<S>,
156{
157    // We *always* want to explicitly set the possible responses, beacuse the
158    // infered ones are not necessarily correct
159    aide::generate::infer_responses(false);
160
161    aide::generate::in_context(|ctx| {
162        ctx.schema =
163            schemars::r#gen::SchemaGenerator::new(schemars::r#gen::SchemaSettings::openapi3());
164    });
165
166    let mut api = OpenApi::default();
167    let router = ApiRouter::<S>::new()
168        .nest("/api/admin/v1", self::v1::router())
169        .finish_api_with(&mut api, finish);
170
171    let router = router
172        // Serve the OpenAPI spec as JSON
173        .route(
174            "/api/spec.json",
175            axum::routing::get({
176                let api = api.clone();
177                move |State(url_builder): State<UrlBuilder>| {
178                    // Let's set the servers to the HTTP base URL
179                    let mut api = api.clone();
180
181                    let _ = TransformOpenApi::new(&mut api)
182                        .server(Server {
183                            url: url_builder.http_base().to_string(),
184                            ..Server::default()
185                        })
186                        .security_scheme("oauth2", oauth_security_scheme(Some(&url_builder)));
187
188                    std::future::ready(Json(api))
189                }
190            }),
191        )
192        // Serve the Swagger API reference
193        .route(ApiDoc::route(), axum::routing::get(swagger))
194        .route(
195            ApiDocCallback::route(),
196            axum::routing::get(swagger_callback),
197        )
198        .layer(
199            CorsLayer::new()
200                .allow_origin(Any)
201                .allow_methods(Any)
202                .allow_otel_headers([
203                    AUTHORIZATION,
204                    ACCEPT,
205                    CONTENT_TYPE,
206                    // Swagger will send this header, so we have to allow it to avoid CORS errors
207                    HeaderName::from_static("x-requested-with"),
208                ]),
209        );
210
211    (api, router)
212}
213
214async fn swagger(
215    State(url_builder): State<UrlBuilder>,
216    State(templates): State<Templates>,
217) -> Result<Html<String>, InternalError> {
218    let ctx = ApiDocContext::from_url_builder(&url_builder);
219    let res = templates.render_swagger(&ctx)?;
220    Ok(Html(res))
221}
222
223async fn swagger_callback(
224    State(url_builder): State<UrlBuilder>,
225    State(templates): State<Templates>,
226) -> Result<Html<String>, InternalError> {
227    let ctx = ApiDocContext::from_url_builder(&url_builder);
228    let res = templates.render_swagger_callback(&ctx)?;
229    Ok(Html(res))
230}