1use 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_data_model::{BoxRng, SiteConfig};
24use mas_http::CorsLayerExt;
25use mas_matrix::HomeserverConnection;
26use mas_policy::PolicyFactory;
27use mas_router::{
28 ApiDoc, ApiDocCallback, OAuth2AuthorizationEndpoint, OAuth2TokenEndpoint, Route, SimpleRoute,
29 UrlBuilder,
30};
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: "server".to_owned(),
48 description: Some("Information about the server".to_owned()),
49 ..Tag::default()
50 })
51 .tag(Tag {
52 name: "compat-session".to_owned(),
53 description: Some("Manage compatibility sessions from legacy clients".to_owned()),
54 ..Tag::default()
55 })
56 .tag(Tag {
57 name: "policy-data".to_owned(),
58 description: Some("Manage the dynamic policy data".to_owned()),
59 ..Tag::default()
60 })
61 .tag(Tag {
62 name: "oauth2-session".to_owned(),
63 description: Some("Manage OAuth2 sessions".to_owned()),
64 ..Tag::default()
65 })
66 .tag(Tag {
67 name: "user".to_owned(),
68 description: Some("Manage users".to_owned()),
69 ..Tag::default()
70 })
71 .tag(Tag {
72 name: "user-email".to_owned(),
73 description: Some("Manage emails associated with users".to_owned()),
74 ..Tag::default()
75 })
76 .tag(Tag {
77 name: "user-session".to_owned(),
78 description: Some("Manage browser sessions of users".to_owned()),
79 ..Tag::default()
80 })
81 .tag(Tag {
82 name: "user-registration-token".to_owned(),
83 description: Some("Manage user registration tokens".to_owned()),
84 ..Tag::default()
85 })
86 .tag(Tag {
87 name: "upstream-oauth-link".to_owned(),
88 description: Some(
89 "Manage links between local users and identities from upstream OAuth 2.0 providers"
90 .to_owned(),
91 ),
92 ..Default::default()
93 })
94 .security_scheme("oauth2", oauth_security_scheme(None))
95 .security_scheme(
96 "token",
97 SecurityScheme::Http {
98 scheme: "bearer".to_owned(),
99 bearer_format: None,
100 description: Some("An access token with access to the admin API".to_owned()),
101 extensions: IndexMap::default(),
102 },
103 )
104 .security_requirement_scopes("oauth2", ["urn:mas:admin"])
105 .security_requirement_scopes("bearer", ["urn:mas:admin"])
106}
107
108fn oauth_security_scheme(url_builder: Option<&UrlBuilder>) -> SecurityScheme {
109 let (authorization_url, token_url) = if let Some(url_builder) = url_builder {
110 (
111 url_builder.oauth_authorization_endpoint().to_string(),
112 url_builder.oauth_token_endpoint().to_string(),
113 )
114 } else {
115 (
120 format!(".{}", OAuth2AuthorizationEndpoint::PATH),
121 format!(".{}", OAuth2TokenEndpoint::PATH),
122 )
123 };
124
125 let scopes = IndexMap::from([(
126 "urn:mas:admin".to_owned(),
127 "Grant access to the admin API".to_owned(),
128 )]);
129
130 SecurityScheme::OAuth2 {
131 flows: OAuth2Flows {
132 client_credentials: Some(OAuth2Flow::ClientCredentials {
133 refresh_url: Some(token_url.clone()),
134 token_url: token_url.clone(),
135 scopes: scopes.clone(),
136 }),
137 authorization_code: Some(OAuth2Flow::AuthorizationCode {
138 authorization_url,
139 refresh_url: Some(token_url.clone()),
140 token_url,
141 scopes,
142 }),
143 implicit: None,
144 password: None,
145 },
146 description: None,
147 extensions: IndexMap::default(),
148 }
149}
150
151pub fn router<S>() -> (OpenApi, Router<S>)
152where
153 S: Clone + Send + Sync + 'static,
154 Arc<dyn HomeserverConnection>: FromRef<S>,
155 PasswordManager: FromRef<S>,
156 BoxRng: FromRequestParts<S>,
157 CallContext: FromRequestParts<S>,
158 Templates: FromRef<S>,
159 UrlBuilder: FromRef<S>,
160 Arc<PolicyFactory>: FromRef<S>,
161 SiteConfig: FromRef<S>,
162{
163 aide::generate::infer_responses(false);
166
167 aide::generate::in_context(|ctx| {
168 ctx.schema =
169 schemars::r#gen::SchemaGenerator::new(schemars::r#gen::SchemaSettings::openapi3());
170 });
171
172 let mut api = OpenApi::default();
173 let router = ApiRouter::<S>::new()
174 .nest("/api/admin/v1", self::v1::router())
175 .finish_api_with(&mut api, finish);
176
177 let router = router
178 .route(
180 "/api/spec.json",
181 axum::routing::get({
182 let api = api.clone();
183 move |State(url_builder): State<UrlBuilder>| {
184 let mut api = api.clone();
186
187 let _ = TransformOpenApi::new(&mut api)
188 .server(Server {
189 url: url_builder.http_base().to_string(),
190 ..Server::default()
191 })
192 .security_scheme("oauth2", oauth_security_scheme(Some(&url_builder)));
193
194 std::future::ready(Json(api))
195 }
196 }),
197 )
198 .route(ApiDoc::route(), axum::routing::get(swagger))
200 .route(
201 ApiDocCallback::route(),
202 axum::routing::get(swagger_callback),
203 )
204 .layer(
205 CorsLayer::new()
206 .allow_origin(Any)
207 .allow_methods(Any)
208 .allow_otel_headers([
209 AUTHORIZATION,
210 ACCEPT,
211 CONTENT_TYPE,
212 HeaderName::from_static("x-requested-with"),
214 ]),
215 );
216
217 (api, router)
218}
219
220async fn swagger(
221 State(url_builder): State<UrlBuilder>,
222 State(templates): State<Templates>,
223) -> Result<Html<String>, InternalError> {
224 let ctx = ApiDocContext::from_url_builder(&url_builder);
225 let res = templates.render_swagger(&ctx)?;
226 Ok(Html(res))
227}
228
229async fn swagger_callback(
230 State(url_builder): State<UrlBuilder>,
231 State(templates): State<Templates>,
232) -> Result<Html<String>, InternalError> {
233 let ctx = ApiDocContext::from_url_builder(&url_builder);
234 let res = templates.render_swagger_callback(&ctx)?;
235 Ok(Html(res))
236}