Skip to content
This repository was archived by the owner on Sep 10, 2024. It is now read-only.

Commit b1b85e7

Browse files
committed
admin: user deactivation API
1 parent 82ce8a7 commit b1b85e7

File tree

4 files changed

+290
-1
lines changed

4 files changed

+290
-1
lines changed

crates/handlers/src/admin/v1/mod.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
use aide::axum::{routing::get_with, ApiRouter};
15+
use aide::axum::{
16+
routing::{get_with, post_with},
17+
ApiRouter,
18+
};
1619
use axum::extract::{FromRef, FromRequestParts};
1720
use mas_matrix::BoxHomeserverConnection;
1821
use mas_storage::BoxRng;
@@ -42,4 +45,8 @@ where
4245
"/users/by-username/:username",
4346
get_with(self::users::by_username, self::users::by_username_doc),
4447
)
48+
.api_route(
49+
"/users/:id/deactivate",
50+
post_with(self::users::deactivate, self::users::deactivate_doc),
51+
)
4552
}
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
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+
}

crates/handlers/src/admin/v1/users/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,14 @@
1414

1515
mod add;
1616
mod by_username;
17+
mod deactivate;
1718
mod get;
1819
mod list;
1920

2021
pub use self::{
2122
add::{doc as add_doc, handler as add},
2223
by_username::{doc as by_username_doc, handler as by_username},
24+
deactivate::{doc as deactivate_doc, handler as deactivate},
2325
get::{doc as get_doc, handler as get},
2426
list::{doc as list_doc, handler as list},
2527
};

docs/api/spec.json

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,77 @@
389389
}
390390
}
391391
}
392+
},
393+
"/api/admin/v1/users/{id}/deactivate": {
394+
"post": {
395+
"tags": [
396+
"user"
397+
],
398+
"summary": "Deactivate a user",
399+
"description": "Calling this endpoint will lock and deactivate the user, preventing them from doing any action.\nThis invalidates any existing session, and will ask the homeserver to make them leave all rooms.",
400+
"parameters": [
401+
{
402+
"in": "path",
403+
"name": "id",
404+
"description": "A ULID as per https://github.com/ulid/spec",
405+
"required": true,
406+
"schema": {
407+
"title": "ULID",
408+
"description": "A ULID as per https://github.com/ulid/spec",
409+
"type": "string",
410+
"pattern": "^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$"
411+
},
412+
"style": "simple"
413+
}
414+
],
415+
"responses": {
416+
"200": {
417+
"description": "User was deactivated",
418+
"content": {
419+
"application/json": {
420+
"schema": {
421+
"$ref": "#/components/schemas/SingleResponse_for_User"
422+
},
423+
"example": {
424+
"data": {
425+
"type": "user",
426+
"id": "030C1G60R30C1G60R30C1G60R3",
427+
"attributes": {
428+
"username": "charlie",
429+
"created_at": "1970-01-01T00:00:00Z",
430+
"locked_at": "1970-01-01T00:00:00Z",
431+
"can_request_admin": false
432+
},
433+
"links": {
434+
"self": "/api/admin/v1/users/030C1G60R30C1G60R30C1G60R3"
435+
}
436+
},
437+
"links": {
438+
"self": "/api/admin/v1/users/030C1G60R30C1G60R30C1G60R3/deactivate"
439+
}
440+
}
441+
}
442+
}
443+
},
444+
"404": {
445+
"description": "User ID not found",
446+
"content": {
447+
"application/json": {
448+
"schema": {
449+
"$ref": "#/components/schemas/ErrorResponse"
450+
},
451+
"example": {
452+
"errors": [
453+
{
454+
"title": "User ID 00000000000000000000000000 not found"
455+
}
456+
]
457+
}
458+
}
459+
}
460+
}
461+
}
462+
}
392463
}
393464
},
394465
"components": {

0 commit comments

Comments
 (0)