|
| 1 | +// Copyright 2024 The Matrix.org Foundation C.I.C. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use aide::{transform::TransformOperation, NoApi, OperationIo}; |
| 16 | +use axum::{extract::State, response::IntoResponse, Json}; |
| 17 | +use hyper::StatusCode; |
| 18 | +use mas_matrix::BoxHomeserverConnection; |
| 19 | +use mas_storage::{ |
| 20 | + job::{JobRepositoryExt, ProvisionUserJob}, |
| 21 | + BoxRng, |
| 22 | +}; |
| 23 | +use schemars::JsonSchema; |
| 24 | +use serde::Deserialize; |
| 25 | +use tracing::warn; |
| 26 | + |
| 27 | +use crate::{ |
| 28 | + admin::{ |
| 29 | + call_context::CallContext, |
| 30 | + model::User, |
| 31 | + response::{ErrorResponse, SingleResponse}, |
| 32 | + }, |
| 33 | + impl_from_error_for_route, |
| 34 | +}; |
| 35 | + |
| 36 | +fn valid_username_character(c: char) -> bool { |
| 37 | + c.is_ascii_lowercase() |
| 38 | + || c.is_ascii_digit() |
| 39 | + || c == '=' |
| 40 | + || c == '_' |
| 41 | + || c == '-' |
| 42 | + || c == '.' |
| 43 | + || c == '/' |
| 44 | + || c == '+' |
| 45 | +} |
| 46 | + |
| 47 | +// XXX: this should be shared with the graphql handler |
| 48 | +fn username_valid(username: &str) -> bool { |
| 49 | + if username.is_empty() || username.len() > 255 { |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + // Should not start with an underscore |
| 54 | + if username.get(0..1) == Some("_") { |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | + // Should only contain valid characters |
| 59 | + if !username.chars().all(valid_username_character) { |
| 60 | + return false; |
| 61 | + } |
| 62 | + |
| 63 | + true |
| 64 | +} |
| 65 | + |
| 66 | +#[derive(Debug, thiserror::Error, OperationIo)] |
| 67 | +#[aide(output_with = "Json<ErrorResponse>")] |
| 68 | +pub enum RouteError { |
| 69 | + #[error(transparent)] |
| 70 | + Internal(Box<dyn std::error::Error + Send + Sync + 'static>), |
| 71 | + |
| 72 | + #[error(transparent)] |
| 73 | + Homeserver(anyhow::Error), |
| 74 | + |
| 75 | + #[error("Username is not valid")] |
| 76 | + UsernameNotValid, |
| 77 | + |
| 78 | + #[error("User already exists")] |
| 79 | + UserAlreadyExists, |
| 80 | + |
| 81 | + #[error("Username is reserved by the homeserver")] |
| 82 | + UsernameReserved, |
| 83 | +} |
| 84 | + |
| 85 | +impl_from_error_for_route!(mas_storage::RepositoryError); |
| 86 | + |
| 87 | +impl IntoResponse for RouteError { |
| 88 | + fn into_response(self) -> axum::response::Response { |
| 89 | + let error = ErrorResponse::from_error(&self); |
| 90 | + let status = match self { |
| 91 | + Self::Internal(_) | Self::Homeserver(_) => StatusCode::INTERNAL_SERVER_ERROR, |
| 92 | + Self::UsernameNotValid => StatusCode::BAD_REQUEST, |
| 93 | + Self::UserAlreadyExists | Self::UsernameReserved => StatusCode::CONFLICT, |
| 94 | + }; |
| 95 | + (status, Json(error)).into_response() |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +#[derive(Deserialize, JsonSchema)] |
| 100 | +pub struct AddUserParams { |
| 101 | + /// The username of the user to add. |
| 102 | + username: String, |
| 103 | + |
| 104 | + /// Skip checking with the homeserver whether the username is valid. |
| 105 | + /// |
| 106 | + /// Use this with caution! The main reason to use this, is when a user used |
| 107 | + /// by an application service needs to exist in MAS to craft special |
| 108 | + /// tokens (like with admin access) for them |
| 109 | + #[serde(default)] |
| 110 | + skip_homeserver_check: bool, |
| 111 | +} |
| 112 | + |
| 113 | +pub fn doc(operation: TransformOperation) -> TransformOperation { |
| 114 | + operation |
| 115 | + .summary("Create a new user") |
| 116 | + .tag("user") |
| 117 | + .response_with::<200, Json<SingleResponse<User>>, _>(|t| { |
| 118 | + let [sample, ..] = User::samples(); |
| 119 | + let response = SingleResponse::new_canonical(sample); |
| 120 | + t.description("User was created").example(response) |
| 121 | + }) |
| 122 | + .response_with::<400, RouteError, _>(|t| { |
| 123 | + let response = ErrorResponse::from_error(&RouteError::UsernameNotValid); |
| 124 | + t.description("Username is not valid").example(response) |
| 125 | + }) |
| 126 | + .response_with::<409, RouteError, _>(|t| { |
| 127 | + let response = ErrorResponse::from_error(&RouteError::UserAlreadyExists); |
| 128 | + t.description("User already exists").example(response) |
| 129 | + }) |
| 130 | + .response_with::<409, RouteError, _>(|t| { |
| 131 | + let response = ErrorResponse::from_error(&RouteError::UsernameReserved); |
| 132 | + t.description("Username is reserved by the homeserver") |
| 133 | + .example(response) |
| 134 | + }) |
| 135 | +} |
| 136 | + |
| 137 | +#[tracing::instrument(name = "handler.admin.v1.users.add", skip_all, err)] |
| 138 | +pub async fn handler( |
| 139 | + CallContext { |
| 140 | + mut repo, clock, .. |
| 141 | + }: CallContext, |
| 142 | + NoApi(mut rng): NoApi<BoxRng>, |
| 143 | + State(homeserver): State<BoxHomeserverConnection>, |
| 144 | + Json(params): Json<AddUserParams>, |
| 145 | +) -> Result<Json<SingleResponse<User>>, RouteError> { |
| 146 | + if repo.user().exists(¶ms.username).await? { |
| 147 | + return Err(RouteError::UserAlreadyExists); |
| 148 | + } |
| 149 | + |
| 150 | + // Do some basic check on the username |
| 151 | + if !username_valid(¶ms.username) { |
| 152 | + return Err(RouteError::UsernameNotValid); |
| 153 | + } |
| 154 | + |
| 155 | + // Ask the homeserver if the username is available |
| 156 | + let homeserver_available = homeserver |
| 157 | + .is_localpart_available(¶ms.username) |
| 158 | + .await |
| 159 | + .map_err(RouteError::Homeserver)?; |
| 160 | + |
| 161 | + if !homeserver_available { |
| 162 | + if !params.skip_homeserver_check { |
| 163 | + return Err(RouteError::UsernameReserved); |
| 164 | + } |
| 165 | + |
| 166 | + // If we skipped the check, we still want to shout about it |
| 167 | + warn!("Skipped homeserver check for username {}", params.username); |
| 168 | + } |
| 169 | + |
| 170 | + let user = repo.user().add(&mut rng, &clock, params.username).await?; |
| 171 | + |
| 172 | + repo.job() |
| 173 | + .schedule_job(ProvisionUserJob::new(&user)) |
| 174 | + .await?; |
| 175 | + |
| 176 | + repo.save().await?; |
| 177 | + |
| 178 | + Ok(Json(SingleResponse::new_canonical(User::from(user)))) |
| 179 | +} |
0 commit comments