|
| 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, OperationIo}; |
| 16 | +use axum::{response::IntoResponse, Json}; |
| 17 | +use hyper::StatusCode; |
| 18 | +use mas_storage::job::{DeactivateUserJob, JobRepositoryExt}; |
| 19 | +use tracing::info; |
| 20 | +use ulid::Ulid; |
| 21 | + |
| 22 | +use crate::{ |
| 23 | + admin::{ |
| 24 | + call_context::CallContext, |
| 25 | + model::{Resource, User}, |
| 26 | + params::UlidPathParam, |
| 27 | + response::{ErrorResponse, SingleResponse}, |
| 28 | + }, |
| 29 | + impl_from_error_for_route, |
| 30 | +}; |
| 31 | + |
| 32 | +#[derive(Debug, thiserror::Error, OperationIo)] |
| 33 | +#[aide(output_with = "Json<ErrorResponse>")] |
| 34 | +pub enum RouteError { |
| 35 | + #[error(transparent)] |
| 36 | + Internal(Box<dyn std::error::Error + Send + Sync + 'static>), |
| 37 | + |
| 38 | + #[error("User ID {0} not found")] |
| 39 | + NotFound(Ulid), |
| 40 | +} |
| 41 | + |
| 42 | +impl_from_error_for_route!(mas_storage::RepositoryError); |
| 43 | + |
| 44 | +impl IntoResponse for RouteError { |
| 45 | + fn into_response(self) -> axum::response::Response { |
| 46 | + let error = ErrorResponse::from_error(&self); |
| 47 | + let status = match self { |
| 48 | + Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, |
| 49 | + Self::NotFound(_) => StatusCode::NOT_FOUND, |
| 50 | + }; |
| 51 | + (status, Json(error)).into_response() |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +pub fn doc(operation: TransformOperation) -> TransformOperation { |
| 56 | + operation |
| 57 | + .summary("Deactivate a user") |
| 58 | + .description("Calling this endpoint will lock and deactivate the user, preventing them from doing any action. |
| 59 | +This invalidates any existing session, and will ask the homeserver to make them leave all rooms.") |
| 60 | + .tag("user") |
| 61 | + .response_with::<200, Json<SingleResponse<User>>, _>(|t| { |
| 62 | + // In the samples, the third user is the one locked |
| 63 | + let [_alice, _bob, charlie, ..] = User::samples(); |
| 64 | + let id = charlie.id(); |
| 65 | + let response = SingleResponse::new(charlie, format!("/api/admin/v1/users/{id}/deactivate")); |
| 66 | + t.description("User was deactivated").example(response) |
| 67 | + }) |
| 68 | + .response_with::<404, RouteError, _>(|t| { |
| 69 | + let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil())); |
| 70 | + t.description("User ID not found").example(response) |
| 71 | + }) |
| 72 | +} |
| 73 | + |
| 74 | +#[tracing::instrument(name = "handler.admin.v1.users.deactivate", skip_all, err)] |
| 75 | +pub async fn handler( |
| 76 | + CallContext { |
| 77 | + mut repo, clock, .. |
| 78 | + }: CallContext, |
| 79 | + id: UlidPathParam, |
| 80 | +) -> Result<Json<SingleResponse<User>>, RouteError> { |
| 81 | + let id = *id; |
| 82 | + let mut user = repo |
| 83 | + .user() |
| 84 | + .lookup(id) |
| 85 | + .await? |
| 86 | + .ok_or(RouteError::NotFound(id))?; |
| 87 | + |
| 88 | + if user.locked_at.is_none() { |
| 89 | + user = repo.user().lock(&clock, user).await?; |
| 90 | + } |
| 91 | + |
| 92 | + info!("Scheduling deactivation of user {}", user.id); |
| 93 | + repo.job() |
| 94 | + .schedule_job(DeactivateUserJob::new(&user, true)) |
| 95 | + .await?; |
| 96 | + |
| 97 | + repo.save().await?; |
| 98 | + |
| 99 | + Ok(Json(SingleResponse::new( |
| 100 | + User::from(user), |
| 101 | + format!("/api/admin/v1/users/{id}/deactivate"), |
| 102 | + ))) |
| 103 | +} |
| 104 | + |
| 105 | +#[cfg(test)] |
| 106 | +mod tests { |
| 107 | + use chrono::Duration; |
| 108 | + use hyper::{Request, StatusCode}; |
| 109 | + use mas_storage::{user::UserRepository, Clock, RepositoryAccess}; |
| 110 | + use sqlx::{types::Json, PgPool}; |
| 111 | + |
| 112 | + use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; |
| 113 | + |
| 114 | + #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] |
| 115 | + async fn test_deactivate_user(pool: PgPool) { |
| 116 | + setup(); |
| 117 | + let mut state = TestState::from_pool(pool.clone()).await.unwrap(); |
| 118 | + let token = state.token_with_scope("urn:mas:admin").await; |
| 119 | + |
| 120 | + let mut repo = state.repository().await.unwrap(); |
| 121 | + let user = repo |
| 122 | + .user() |
| 123 | + .add(&mut state.rng(), &state.clock, "alice".to_owned()) |
| 124 | + .await |
| 125 | + .unwrap(); |
| 126 | + repo.save().await.unwrap(); |
| 127 | + |
| 128 | + let request = Request::post(format!("/api/admin/v1/users/{}/deactivate", user.id)) |
| 129 | + .bearer(&token) |
| 130 | + .empty(); |
| 131 | + let response = state.request(request).await; |
| 132 | + response.assert_status(StatusCode::OK); |
| 133 | + let body: serde_json::Value = response.json(); |
| 134 | + |
| 135 | + // The locked_at timestamp should be the same as the current time |
| 136 | + assert_eq!( |
| 137 | + body["data"]["attributes"]["locked_at"], |
| 138 | + serde_json::json!(state.clock.now()) |
| 139 | + ); |
| 140 | + |
| 141 | + // It should have scheduled a deactivation job for the user |
| 142 | + // XXX: we don't have a good way to look for the deactivation job |
| 143 | + let job: Json<serde_json::Value> = |
| 144 | + sqlx::query_scalar("SELECT job FROM apalis.jobs WHERE job_type = 'deactivate-user'") |
| 145 | + .fetch_one(&pool) |
| 146 | + .await |
| 147 | + .expect("Deactivation job to be scheduled"); |
| 148 | + assert_eq!(job["user_id"], serde_json::json!(user.id)); |
| 149 | + } |
| 150 | + |
| 151 | + #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] |
| 152 | + async fn test_deactivate_locked_user(pool: PgPool) { |
| 153 | + setup(); |
| 154 | + let mut state = TestState::from_pool(pool.clone()).await.unwrap(); |
| 155 | + let token = state.token_with_scope("urn:mas:admin").await; |
| 156 | + |
| 157 | + let mut repo = state.repository().await.unwrap(); |
| 158 | + let user = repo |
| 159 | + .user() |
| 160 | + .add(&mut state.rng(), &state.clock, "alice".to_owned()) |
| 161 | + .await |
| 162 | + .unwrap(); |
| 163 | + let user = repo.user().lock(&state.clock, user).await.unwrap(); |
| 164 | + repo.save().await.unwrap(); |
| 165 | + |
| 166 | + // Move the clock forward to make sure the locked_at timestamp doesn't change |
| 167 | + state.clock.advance(Duration::try_minutes(1).unwrap()); |
| 168 | + |
| 169 | + let request = Request::post(format!("/api/admin/v1/users/{}/deactivate", user.id)) |
| 170 | + .bearer(&token) |
| 171 | + .empty(); |
| 172 | + let response = state.request(request).await; |
| 173 | + response.assert_status(StatusCode::OK); |
| 174 | + let body: serde_json::Value = response.json(); |
| 175 | + |
| 176 | + // The locked_at timestamp should be different from the current time |
| 177 | + assert_ne!( |
| 178 | + body["data"]["attributes"]["locked_at"], |
| 179 | + serde_json::json!(state.clock.now()) |
| 180 | + ); |
| 181 | + |
| 182 | + // It should have scheduled a deactivation job for the user |
| 183 | + // XXX: we don't have a good way to look for the deactivation job |
| 184 | + let job: Json<serde_json::Value> = |
| 185 | + sqlx::query_scalar("SELECT job FROM apalis.jobs WHERE job_type = 'deactivate-user'") |
| 186 | + .fetch_one(&pool) |
| 187 | + .await |
| 188 | + .expect("Deactivation job to be scheduled"); |
| 189 | + assert_eq!(job["user_id"], serde_json::json!(user.id)); |
| 190 | + } |
| 191 | + |
| 192 | + #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] |
| 193 | + async fn test_deactivate_unknown_user(pool: PgPool) { |
| 194 | + setup(); |
| 195 | + let mut state = TestState::from_pool(pool).await.unwrap(); |
| 196 | + let token = state.token_with_scope("urn:mas:admin").await; |
| 197 | + |
| 198 | + let request = Request::post("/api/admin/v1/users/01040G2081040G2081040G2081/deactivate") |
| 199 | + .bearer(&token) |
| 200 | + .empty(); |
| 201 | + let response = state.request(request).await; |
| 202 | + response.assert_status(StatusCode::NOT_FOUND); |
| 203 | + let body: serde_json::Value = response.json(); |
| 204 | + assert_eq!( |
| 205 | + body["errors"][0]["title"], |
| 206 | + "User ID 01040G2081040G2081040G2081 not found" |
| 207 | + ); |
| 208 | + } |
| 209 | +} |
0 commit comments