|
| 1 | +// Copyright 2025 New Vector Ltd. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial |
| 4 | +// Please see LICENSE files in the repository root for full details. |
| 5 | + |
| 6 | +use aide::{NoApi, OperationIo, transform::TransformOperation}; |
| 7 | +use axum::{Json, response::IntoResponse}; |
| 8 | +use hyper::StatusCode; |
| 9 | +use mas_axum_utils::record_error; |
| 10 | +use mas_storage::{ |
| 11 | + BoxRng, |
| 12 | + queue::{QueueJobRepositoryExt as _, ReactivateUserJob}, |
| 13 | +}; |
| 14 | +use tracing::info; |
| 15 | +use ulid::Ulid; |
| 16 | + |
| 17 | +use crate::{ |
| 18 | + admin::{ |
| 19 | + call_context::CallContext, |
| 20 | + model::{Resource, User}, |
| 21 | + params::UlidPathParam, |
| 22 | + response::{ErrorResponse, SingleResponse}, |
| 23 | + }, |
| 24 | + impl_from_error_for_route, |
| 25 | +}; |
| 26 | + |
| 27 | +#[derive(Debug, thiserror::Error, OperationIo)] |
| 28 | +#[aide(output_with = "Json<ErrorResponse>")] |
| 29 | +pub enum RouteError { |
| 30 | + #[error(transparent)] |
| 31 | + Internal(Box<dyn std::error::Error + Send + Sync + 'static>), |
| 32 | + |
| 33 | + #[error("User ID {0} not found")] |
| 34 | + NotFound(Ulid), |
| 35 | +} |
| 36 | + |
| 37 | +impl_from_error_for_route!(mas_storage::RepositoryError); |
| 38 | + |
| 39 | +impl IntoResponse for RouteError { |
| 40 | + fn into_response(self) -> axum::response::Response { |
| 41 | + let error = ErrorResponse::from_error(&self); |
| 42 | + let sentry_event_id = record_error!(self, Self::Internal(_)); |
| 43 | + let status = match self { |
| 44 | + Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, |
| 45 | + Self::NotFound(_) => StatusCode::NOT_FOUND, |
| 46 | + }; |
| 47 | + (status, sentry_event_id, Json(error)).into_response() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +pub fn doc(operation: TransformOperation) -> TransformOperation { |
| 52 | + operation |
| 53 | + .id("reactivateUser") |
| 54 | + .summary("Reactivate a user") |
| 55 | + .description("Calling this endpoint will reactivate a deactivated user, both locally and on the Matrix homeserver.") |
| 56 | + .tag("user") |
| 57 | + .response_with::<200, Json<SingleResponse<User>>, _>(|t| { |
| 58 | + // In the samples, the third user is the one locked |
| 59 | + let [sample, ..] = User::samples(); |
| 60 | + let id = sample.id(); |
| 61 | + let response = SingleResponse::new(sample, format!("/api/admin/v1/users/{id}/reactivate")); |
| 62 | + t.description("User was reactivated").example(response) |
| 63 | + }) |
| 64 | + .response_with::<404, RouteError, _>(|t| { |
| 65 | + let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil())); |
| 66 | + t.description("User ID not found").example(response) |
| 67 | + }) |
| 68 | +} |
| 69 | + |
| 70 | +#[tracing::instrument(name = "handler.admin.v1.users.reactivate", skip_all)] |
| 71 | +pub async fn handler( |
| 72 | + CallContext { |
| 73 | + mut repo, clock, .. |
| 74 | + }: CallContext, |
| 75 | + NoApi(mut rng): NoApi<BoxRng>, |
| 76 | + id: UlidPathParam, |
| 77 | +) -> Result<Json<SingleResponse<User>>, RouteError> { |
| 78 | + let id = *id; |
| 79 | + let user = repo |
| 80 | + .user() |
| 81 | + .lookup(id) |
| 82 | + .await? |
| 83 | + .ok_or(RouteError::NotFound(id))?; |
| 84 | + |
| 85 | + info!(%user.id, "Scheduling reactivation of user"); |
| 86 | + repo.queue_job() |
| 87 | + .schedule_job(&mut rng, &clock, ReactivateUserJob::new(&user, false)) |
| 88 | + .await?; |
| 89 | + |
| 90 | + repo.save().await?; |
| 91 | + |
| 92 | + Ok(Json(SingleResponse::new( |
| 93 | + User::from(user), |
| 94 | + format!("/api/admin/v1/users/{id}/reactivate"), |
| 95 | + ))) |
| 96 | +} |
| 97 | + |
| 98 | +#[cfg(test)] |
| 99 | +mod tests { |
| 100 | + use hyper::{Request, StatusCode}; |
| 101 | + use mas_matrix::{HomeserverConnection, ProvisionRequest}; |
| 102 | + use mas_storage::{Clock, RepositoryAccess, user::UserRepository}; |
| 103 | + use sqlx::{PgPool, types::Json}; |
| 104 | + |
| 105 | + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; |
| 106 | + |
| 107 | + #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] |
| 108 | + async fn test_reactivate_deactivated_user(pool: PgPool) { |
| 109 | + setup(); |
| 110 | + let mut state = TestState::from_pool(pool.clone()).await.unwrap(); |
| 111 | + let token = state.token_with_scope("urn:mas:admin").await; |
| 112 | + |
| 113 | + let mut repo = state.repository().await.unwrap(); |
| 114 | + let user = repo |
| 115 | + .user() |
| 116 | + .add(&mut state.rng(), &state.clock, "alice".to_owned()) |
| 117 | + .await |
| 118 | + .unwrap(); |
| 119 | + let user = repo.user().lock(&state.clock, user).await.unwrap(); |
| 120 | + let user = repo.user().deactivate(&state.clock, user).await.unwrap(); |
| 121 | + repo.save().await.unwrap(); |
| 122 | + |
| 123 | + // Provision and immediately deactivate the user on the homeserver, |
| 124 | + // because this endpoint will try to reactivate it |
| 125 | + let mxid = state.homeserver_connection.mxid(&user.username); |
| 126 | + state |
| 127 | + .homeserver_connection |
| 128 | + .provision_user(&ProvisionRequest::new(&mxid, &user.sub)) |
| 129 | + .await |
| 130 | + .unwrap(); |
| 131 | + state |
| 132 | + .homeserver_connection |
| 133 | + .delete_user(&mxid, true) |
| 134 | + .await |
| 135 | + .unwrap(); |
| 136 | + |
| 137 | + // The user should be deactivated on the homeserver |
| 138 | + let mx_user = state.homeserver_connection.query_user(&mxid).await.unwrap(); |
| 139 | + assert!(mx_user.deactivated); |
| 140 | + |
| 141 | + let request = Request::post(format!("/api/admin/v1/users/{}/reactivate", user.id)) |
| 142 | + .bearer(&token) |
| 143 | + .empty(); |
| 144 | + let response = state.request(request).await; |
| 145 | + response.assert_status(StatusCode::OK); |
| 146 | + let body: serde_json::Value = response.json(); |
| 147 | + |
| 148 | + // The user should remain locked after being reactivated |
| 149 | + assert_eq!( |
| 150 | + body["data"]["attributes"]["locked_at"], |
| 151 | + serde_json::json!(state.clock.now()) |
| 152 | + ); |
| 153 | + // TODO: have test coverage on deactivated_at timestamp |
| 154 | + |
| 155 | + // It should have scheduled a reactivation job for the user |
| 156 | + // XXX: we don't have a good way to look for the reactivation job |
| 157 | + let job: Json<serde_json::Value> = sqlx::query_scalar( |
| 158 | + "SELECT payload FROM queue_jobs WHERE queue_name = 'reactivate-user'", |
| 159 | + ) |
| 160 | + .fetch_one(&pool) |
| 161 | + .await |
| 162 | + .expect("Reactivation job to be scheduled"); |
| 163 | + assert_eq!(job["user_id"], serde_json::json!(user.id)); |
| 164 | + assert_eq!(job["unlock"], serde_json::Value::Bool(false)); |
| 165 | + } |
| 166 | + |
| 167 | + #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] |
| 168 | + async fn test_reactivate_active_user(pool: PgPool) { |
| 169 | + setup(); |
| 170 | + let mut state = TestState::from_pool(pool.clone()).await.unwrap(); |
| 171 | + let token = state.token_with_scope("urn:mas:admin").await; |
| 172 | + |
| 173 | + let mut repo = state.repository().await.unwrap(); |
| 174 | + let user = repo |
| 175 | + .user() |
| 176 | + .add(&mut state.rng(), &state.clock, "alice".to_owned()) |
| 177 | + .await |
| 178 | + .unwrap(); |
| 179 | + repo.save().await.unwrap(); |
| 180 | + |
| 181 | + let request = Request::post(format!("/api/admin/v1/users/{}/reactivate", user.id)) |
| 182 | + .bearer(&token) |
| 183 | + .empty(); |
| 184 | + let response = state.request(request).await; |
| 185 | + response.assert_status(StatusCode::OK); |
| 186 | + let body: serde_json::Value = response.json(); |
| 187 | + |
| 188 | + assert_eq!( |
| 189 | + body["data"]["attributes"]["locked_at"], |
| 190 | + serde_json::Value::Null |
| 191 | + ); |
| 192 | + // TODO: have test coverage on deactivated_at timestamp |
| 193 | + |
| 194 | + // It should have scheduled a reactivation job for the user |
| 195 | + // XXX: we don't have a good way to look for the reactivation job |
| 196 | + let job: Json<serde_json::Value> = sqlx::query_scalar( |
| 197 | + "SELECT payload FROM queue_jobs WHERE queue_name = 'reactivate-user'", |
| 198 | + ) |
| 199 | + .fetch_one(&pool) |
| 200 | + .await |
| 201 | + .expect("Reactivation job to be scheduled"); |
| 202 | + assert_eq!(job["user_id"], serde_json::json!(user.id)); |
| 203 | + assert_eq!(job["unlock"], serde_json::Value::Bool(false)); |
| 204 | + } |
| 205 | + |
| 206 | + #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] |
| 207 | + async fn test_reactivate_unknown_user(pool: PgPool) { |
| 208 | + setup(); |
| 209 | + let mut state = TestState::from_pool(pool).await.unwrap(); |
| 210 | + let token = state.token_with_scope("urn:mas:admin").await; |
| 211 | + |
| 212 | + let request = Request::post("/api/admin/v1/users/01040G2081040G2081040G2081/reactivate") |
| 213 | + .bearer(&token) |
| 214 | + .empty(); |
| 215 | + let response = state.request(request).await; |
| 216 | + response.assert_status(StatusCode::NOT_FOUND); |
| 217 | + let body: serde_json::Value = response.json(); |
| 218 | + assert_eq!( |
| 219 | + body["errors"][0]["title"], |
| 220 | + "User ID 01040G2081040G2081040G2081 not found" |
| 221 | + ); |
| 222 | + } |
| 223 | +} |
0 commit comments