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

Commit 97eccf6

Browse files
committed
Merge branch 'quenting/admin-api/user-deactivate' into quenting/admin-api/merge
2 parents 02cd462 + 2858840 commit 97eccf6

File tree

4 files changed

+285
-0
lines changed

4 files changed

+285
-0
lines changed

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,8 @@ where
5353
"/users/:id/unlock",
5454
post_with(self::users::unlock, self::users::unlock_doc),
5555
)
56+
.api_route(
57+
"/users/:id/deactivate",
58+
post_with(self::users::deactivate, self::users::deactivate_doc),
59+
)
5660
}
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
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+
.id("deactivateUser")
58+
.summary("Deactivate a user")
59+
.description("Calling this endpoint will lock and deactivate the user, preventing them from doing any action.
60+
This invalidates any existing session, and will ask the homeserver to make them leave all rooms.")
61+
.tag("user")
62+
.response_with::<200, Json<SingleResponse<User>>, _>(|t| {
63+
// In the samples, the third user is the one locked
64+
let [_alice, _bob, charlie, ..] = User::samples();
65+
let id = charlie.id();
66+
let response = SingleResponse::new(charlie, format!("/api/admin/v1/users/{id}/deactivate"));
67+
t.description("User was deactivated").example(response)
68+
})
69+
.response_with::<404, RouteError, _>(|t| {
70+
let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
71+
t.description("User ID not found").example(response)
72+
})
73+
}
74+
75+
#[tracing::instrument(name = "handler.admin.v1.users.deactivate", skip_all, err)]
76+
pub async fn handler(
77+
CallContext {
78+
mut repo, clock, ..
79+
}: CallContext,
80+
id: UlidPathParam,
81+
) -> Result<Json<SingleResponse<User>>, RouteError> {
82+
let id = *id;
83+
let mut user = repo
84+
.user()
85+
.lookup(id)
86+
.await?
87+
.ok_or(RouteError::NotFound(id))?;
88+
89+
if user.locked_at.is_none() {
90+
user = repo.user().lock(&clock, user).await?;
91+
}
92+
93+
info!("Scheduling deactivation of user {}", user.id);
94+
repo.job()
95+
.schedule_job(DeactivateUserJob::new(&user, true))
96+
.await?;
97+
98+
repo.save().await?;
99+
100+
Ok(Json(SingleResponse::new(
101+
User::from(user),
102+
format!("/api/admin/v1/users/{id}/deactivate"),
103+
)))
104+
}
105+
106+
#[cfg(test)]
107+
mod tests {
108+
use chrono::Duration;
109+
use hyper::{Request, StatusCode};
110+
use mas_storage::{user::UserRepository, Clock, RepositoryAccess};
111+
use sqlx::{types::Json, PgPool};
112+
113+
use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState};
114+
115+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
116+
async fn test_deactivate_user(pool: PgPool) {
117+
setup();
118+
let mut state = TestState::from_pool(pool.clone()).await.unwrap();
119+
let token = state.token_with_scope("urn:mas:admin").await;
120+
121+
let mut repo = state.repository().await.unwrap();
122+
let user = repo
123+
.user()
124+
.add(&mut state.rng(), &state.clock, "alice".to_owned())
125+
.await
126+
.unwrap();
127+
repo.save().await.unwrap();
128+
129+
let request = Request::post(format!("/api/admin/v1/users/{}/deactivate", user.id))
130+
.bearer(&token)
131+
.empty();
132+
let response = state.request(request).await;
133+
response.assert_status(StatusCode::OK);
134+
let body: serde_json::Value = response.json();
135+
136+
// The locked_at timestamp should be the same as the current time
137+
assert_eq!(
138+
body["data"]["attributes"]["locked_at"],
139+
serde_json::json!(state.clock.now())
140+
);
141+
142+
// It should have scheduled a deactivation job for the user
143+
// XXX: we don't have a good way to look for the deactivation job
144+
let job: Json<serde_json::Value> =
145+
sqlx::query_scalar("SELECT job FROM apalis.jobs WHERE job_type = 'deactivate-user'")
146+
.fetch_one(&pool)
147+
.await
148+
.expect("Deactivation job to be scheduled");
149+
assert_eq!(job["user_id"], serde_json::json!(user.id));
150+
}
151+
152+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
153+
async fn test_deactivate_locked_user(pool: PgPool) {
154+
setup();
155+
let mut state = TestState::from_pool(pool.clone()).await.unwrap();
156+
let token = state.token_with_scope("urn:mas:admin").await;
157+
158+
let mut repo = state.repository().await.unwrap();
159+
let user = repo
160+
.user()
161+
.add(&mut state.rng(), &state.clock, "alice".to_owned())
162+
.await
163+
.unwrap();
164+
let user = repo.user().lock(&state.clock, user).await.unwrap();
165+
repo.save().await.unwrap();
166+
167+
// Move the clock forward to make sure the locked_at timestamp doesn't change
168+
state.clock.advance(Duration::try_minutes(1).unwrap());
169+
170+
let request = Request::post(format!("/api/admin/v1/users/{}/deactivate", user.id))
171+
.bearer(&token)
172+
.empty();
173+
let response = state.request(request).await;
174+
response.assert_status(StatusCode::OK);
175+
let body: serde_json::Value = response.json();
176+
177+
// The locked_at timestamp should be different from the current time
178+
assert_ne!(
179+
body["data"]["attributes"]["locked_at"],
180+
serde_json::json!(state.clock.now())
181+
);
182+
183+
// It should have scheduled a deactivation job for the user
184+
// XXX: we don't have a good way to look for the deactivation job
185+
let job: Json<serde_json::Value> =
186+
sqlx::query_scalar("SELECT job FROM apalis.jobs WHERE job_type = 'deactivate-user'")
187+
.fetch_one(&pool)
188+
.await
189+
.expect("Deactivation job to be scheduled");
190+
assert_eq!(job["user_id"], serde_json::json!(user.id));
191+
}
192+
193+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
194+
async fn test_deactivate_unknown_user(pool: PgPool) {
195+
setup();
196+
let mut state = TestState::from_pool(pool).await.unwrap();
197+
let token = state.token_with_scope("urn:mas:admin").await;
198+
199+
let request = Request::post("/api/admin/v1/users/01040G2081040G2081040G2081/deactivate")
200+
.bearer(&token)
201+
.empty();
202+
let response = state.request(request).await;
203+
response.assert_status(StatusCode::NOT_FOUND);
204+
let body: serde_json::Value = response.json();
205+
assert_eq!(
206+
body["errors"][0]["title"],
207+
"User ID 01040G2081040G2081040G2081 not found"
208+
);
209+
}
210+
}

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

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

1515
mod add;
1616
mod by_username;
17+
mod deactivate;
1718
mod get;
1819
mod list;
1920
mod lock;
@@ -22,6 +23,7 @@ mod unlock;
2223
pub use self::{
2324
add::{doc as add_doc, handler as add},
2425
by_username::{doc as by_username_doc, handler as by_username},
26+
deactivate::{doc as deactivate_doc, handler as deactivate},
2527
get::{doc as get_doc, handler as get},
2628
list::{doc as list_doc, handler as list},
2729
lock::{doc as lock_doc, handler as lock},

docs/api/spec.json

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,75 @@
515515
}
516516
}
517517
}
518+
},
519+
"/api/admin/v1/users/{id}/deactivate": {
520+
"post": {
521+
"tags": [
522+
"user"
523+
],
524+
"summary": "Deactivate a user",
525+
"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.",
526+
"operationId": "deactivateUser",
527+
"parameters": [
528+
{
529+
"in": "path",
530+
"name": "id",
531+
"required": true,
532+
"schema": {
533+
"title": "The ID of the resource",
534+
"$ref": "#/components/schemas/ULID"
535+
},
536+
"style": "simple"
537+
}
538+
],
539+
"responses": {
540+
"200": {
541+
"description": "User was deactivated",
542+
"content": {
543+
"application/json": {
544+
"schema": {
545+
"$ref": "#/components/schemas/SingleResponse_for_User"
546+
},
547+
"example": {
548+
"data": {
549+
"type": "user",
550+
"id": "030C1G60R30C1G60R30C1G60R3",
551+
"attributes": {
552+
"username": "charlie",
553+
"created_at": "1970-01-01T00:00:00Z",
554+
"locked_at": "1970-01-01T00:00:00Z",
555+
"can_request_admin": false
556+
},
557+
"links": {
558+
"self": "/api/admin/v1/users/030C1G60R30C1G60R30C1G60R3"
559+
}
560+
},
561+
"links": {
562+
"self": "/api/admin/v1/users/030C1G60R30C1G60R30C1G60R3/deactivate"
563+
}
564+
}
565+
}
566+
}
567+
},
568+
"404": {
569+
"description": "User ID not found",
570+
"content": {
571+
"application/json": {
572+
"schema": {
573+
"$ref": "#/components/schemas/ErrorResponse"
574+
},
575+
"example": {
576+
"errors": [
577+
{
578+
"title": "User ID 00000000000000000000000000 not found"
579+
}
580+
]
581+
}
582+
}
583+
}
584+
}
585+
}
586+
}
518587
}
519588
},
520589
"components": {

0 commit comments

Comments
 (0)