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_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: "upstream-oauth-link".to_owned(),
78 description: Some(
79 "Manage links between local users and identities from upstream OAuth 2.0 providers"
80 .to_owned(),
81 ),
82 ..Default::default()
83 })
84 .security_scheme("oauth2", oauth_security_scheme(None))
85 .security_scheme(
86 "token",
87 SecurityScheme::Http {
88 scheme: "bearer".to_owned(),
89 bearer_format: None,
90 description: Some("An access token with access to the admin API".to_owned()),
91 extensions: IndexMap::default(),
92 },
93 )
94 .security_requirement_scopes("oauth2", ["urn:mas:admin"])
95 .security_requirement_scopes("bearer", ["urn:mas:admin"])
96}
97
98fn oauth_security_scheme(url_builder: Option<&UrlBuilder>) -> SecurityScheme {
99 let (authorization_url, token_url) = if let Some(url_builder) = url_builder {
100 (
101 url_builder.oauth_authorization_endpoint().to_string(),
102 url_builder.oauth_token_endpoint().to_string(),
103 )
104 } else {
105 (
110 format!(".{}", OAuth2AuthorizationEndpoint::PATH),
111 format!(".{}", OAuth2TokenEndpoint::PATH),
112 )
113 };
114
115 let scopes = IndexMap::from([(
116 "urn:mas:admin".to_owned(),
117 "Grant access to the admin API".to_owned(),
118 )]);
119
120 SecurityScheme::OAuth2 {
121 flows: OAuth2Flows {
122 client_credentials: Some(OAuth2Flow::ClientCredentials {
123 refresh_url: Some(token_url.clone()),
124 token_url: token_url.clone(),
125 scopes: scopes.clone(),
126 }),
127 authorization_code: Some(OAuth2Flow::AuthorizationCode {
128 authorization_url,
129 refresh_url: Some(token_url.clone()),
130 token_url,
131 scopes,
132 }),
133 implicit: None,
134 password: None,
135 },
136 description: None,
137 extensions: IndexMap::default(),
138 }
139}
140
141pub fn router<S>() -> (OpenApi, Router<S>)
142where
143 S: Clone + Send + Sync + 'static,
144 Arc<dyn HomeserverConnection>: FromRef<S>,
145 PasswordManager: FromRef<S>,
146 BoxRng: FromRequestParts<S>,
147 CallContext: FromRequestParts<S>,
148 Templates: FromRef<S>,
149 UrlBuilder: FromRef<S>,
150 Arc<PolicyFactory>: FromRef<S>,
151{
152 aide::generate::infer_responses(false);
155
156 aide::generate::in_context(|ctx| {
157 ctx.schema =
158 schemars::r#gen::SchemaGenerator::new(schemars::r#gen::SchemaSettings::openapi3());
159 });
160
161 let mut api = OpenApi::default();
162 let router = ApiRouter::<S>::new()
163 .nest("/api/admin/v1", self::v1::router())
164 .finish_api_with(&mut api, finish);
165
166 let router = router
167 .route(
169 "/api/spec.json",
170 axum::routing::get({
171 let api = api.clone();
172 move |State(url_builder): State<UrlBuilder>| {
173 let mut api = api.clone();
175
176 let _ = TransformOpenApi::new(&mut api)
177 .server(Server {
178 url: url_builder.http_base().to_string(),
179 ..Server::default()
180 })
181 .security_scheme("oauth2", oauth_security_scheme(Some(&url_builder)));
182
183 std::future::ready(Json(api))
184 }
185 }),
186 )
187 .route(ApiDoc::route(), axum::routing::get(swagger))
189 .route(
190 ApiDocCallback::route(),
191 axum::routing::get(swagger_callback),
192 )
193 .layer(
194 CorsLayer::new()
195 .allow_origin(Any)
196 .allow_methods(Any)
197 .allow_otel_headers([
198 AUTHORIZATION,
199 ACCEPT,
200 CONTENT_TYPE,
201 HeaderName::from_static("x-requested-with"),
203 ]),
204 );
205
206 (api, router)
207}
208
209async fn swagger(
210 State(url_builder): State<UrlBuilder>,
211 State(templates): State<Templates>,
212) -> Result<Html<String>, InternalError> {
213 let ctx = ApiDocContext::from_url_builder(&url_builder);
214 let res = templates.render_swagger(&ctx)?;
215 Ok(Html(res))
216}
217
218async fn swagger_callback(
219 State(url_builder): State<UrlBuilder>,
220 State(templates): State<Templates>,
221) -> Result<Html<String>, InternalError> {
222 let ctx = ApiDocContext::from_url_builder(&url_builder);
223 let res = templates.render_swagger_callback(&ctx)?;
224 Ok(Html(res))
225}