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

Commit e47674e

Browse files
committed
admin: lock user API
1 parent f382846 commit e47674e

File tree

4 files changed

+262
-1
lines changed

4 files changed

+262
-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/lock",
50+
post_with(self::users::lock, self::users::lock_doc),
51+
)
4552
}
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
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 ulid::Ulid;
19+
20+
use crate::{
21+
admin::{
22+
call_context::CallContext,
23+
model::{Resource, User},
24+
params::UlidPathParam,
25+
response::{ErrorResponse, SingleResponse},
26+
},
27+
impl_from_error_for_route,
28+
};
29+
30+
#[derive(Debug, thiserror::Error, OperationIo)]
31+
#[aide(output_with = "Json<ErrorResponse>")]
32+
pub enum RouteError {
33+
#[error(transparent)]
34+
Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
35+
36+
#[error("User ID {0} not found")]
37+
NotFound(Ulid),
38+
}
39+
40+
impl_from_error_for_route!(mas_storage::RepositoryError);
41+
42+
impl IntoResponse for RouteError {
43+
fn into_response(self) -> axum::response::Response {
44+
let error = ErrorResponse::from_error(&self);
45+
let status = match self {
46+
Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
47+
Self::NotFound(_) => StatusCode::NOT_FOUND,
48+
};
49+
(status, Json(error)).into_response()
50+
}
51+
}
52+
53+
pub fn doc(operation: TransformOperation) -> TransformOperation {
54+
operation
55+
.summary("Lock a user")
56+
.description("Calling this endpoint will lock the user, preventing them from doing any action.
57+
This DOES NOT invalidate any existing session, meaning that all their existing sessions will work again as soon as they get unlocked.")
58+
.tag("user")
59+
.response_with::<200, Json<SingleResponse<User>>, _>(|t| {
60+
// In the samples, the third user is the one locked
61+
let [_alice, _bob, charlie, ..] = User::samples();
62+
let id = charlie.id();
63+
let response = SingleResponse::new(charlie, format!("/api/admin/v1/users/{id}/lock"));
64+
t.description("User was locked").example(response)
65+
})
66+
.response_with::<404, RouteError, _>(|t| {
67+
let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
68+
t.description("User ID not found").example(response)
69+
})
70+
}
71+
72+
#[tracing::instrument(name = "handler.admin.v1.users.lock", skip_all, err)]
73+
pub async fn handler(
74+
CallContext {
75+
mut repo, clock, ..
76+
}: CallContext,
77+
id: UlidPathParam,
78+
) -> Result<Json<SingleResponse<User>>, RouteError> {
79+
let id = *id;
80+
let mut user = repo
81+
.user()
82+
.lookup(id)
83+
.await?
84+
.ok_or(RouteError::NotFound(id))?;
85+
86+
if user.locked_at.is_none() {
87+
user = repo.user().lock(&clock, user).await?;
88+
}
89+
90+
repo.save().await?;
91+
92+
Ok(Json(SingleResponse::new(
93+
User::from(user),
94+
format!("/api/admin/v1/users/{id}/lock"),
95+
)))
96+
}
97+
98+
#[cfg(test)]
99+
mod tests {
100+
use chrono::Duration;
101+
use hyper::{Request, StatusCode};
102+
use mas_storage::{user::UserRepository, Clock, RepositoryAccess};
103+
use sqlx::PgPool;
104+
105+
use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState};
106+
107+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
108+
async fn test_lock_user(pool: PgPool) {
109+
setup();
110+
let mut state = TestState::from_pool(pool).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+
repo.save().await.unwrap();
120+
121+
let request = Request::post(format!("/api/admin/v1/users/{}/lock", user.id))
122+
.bearer(&token)
123+
.empty();
124+
let response = state.request(request).await;
125+
response.assert_status(StatusCode::OK);
126+
let body: serde_json::Value = response.json();
127+
128+
// The locked_at timestamp should be the same as the current time
129+
assert_eq!(
130+
body["data"]["attributes"]["locked_at"],
131+
serde_json::json!(state.clock.now())
132+
);
133+
}
134+
135+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
136+
async fn test_lock_user_twice(pool: PgPool) {
137+
setup();
138+
let mut state = TestState::from_pool(pool).await.unwrap();
139+
let token = state.token_with_scope("urn:mas:admin").await;
140+
141+
let mut repo = state.repository().await.unwrap();
142+
let user = repo
143+
.user()
144+
.add(&mut state.rng(), &state.clock, "alice".to_owned())
145+
.await
146+
.unwrap();
147+
let user = repo.user().lock(&state.clock, user).await.unwrap();
148+
repo.save().await.unwrap();
149+
150+
// Move the clock forward to make sure the locked_at timestamp doesn't change
151+
state.clock.advance(Duration::try_minutes(1).unwrap());
152+
153+
let request = Request::post(format!("/api/admin/v1/users/{}/lock", user.id))
154+
.bearer(&token)
155+
.empty();
156+
let response = state.request(request).await;
157+
response.assert_status(StatusCode::OK);
158+
let body: serde_json::Value = response.json();
159+
160+
// The locked_at timestamp should be different from the current time
161+
assert_ne!(
162+
body["data"]["attributes"]["locked_at"],
163+
serde_json::json!(state.clock.now())
164+
);
165+
}
166+
167+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
168+
async fn test_lock_unknown_user(pool: PgPool) {
169+
setup();
170+
let mut state = TestState::from_pool(pool).await.unwrap();
171+
let token = state.token_with_scope("urn:mas:admin").await;
172+
173+
let request = Request::post("/api/admin/v1/users/01040G2081040G2081040G2081/lock")
174+
.bearer(&token)
175+
.empty();
176+
let response = state.request(request).await;
177+
response.assert_status(StatusCode::NOT_FOUND);
178+
let body: serde_json::Value = response.json();
179+
assert_eq!(
180+
body["errors"][0]["title"],
181+
"User ID 01040G2081040G2081040G2081 not found"
182+
);
183+
}
184+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,12 @@ mod add;
1616
mod by_username;
1717
mod get;
1818
mod list;
19+
mod lock;
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},
2324
get::{doc as get_doc, handler as get},
2425
list::{doc as list_doc, handler as list},
26+
lock::{doc as lock_doc, handler as lock},
2527
};

docs/api/spec.json

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,74 @@
370370
}
371371
}
372372
}
373+
},
374+
"/api/admin/v1/users/{id}/lock": {
375+
"post": {
376+
"tags": [
377+
"user"
378+
],
379+
"summary": "Lock a user",
380+
"description": "Calling this endpoint will lock the user, preventing them from doing any action.\nThis DOES NOT invalidate any existing session, meaning that all their existing sessions will work again as soon as they get unlocked.",
381+
"parameters": [
382+
{
383+
"in": "path",
384+
"name": "id",
385+
"required": true,
386+
"schema": {
387+
"title": "The ID of the resource",
388+
"$ref": "#/components/schemas/ULID"
389+
},
390+
"style": "simple"
391+
}
392+
],
393+
"responses": {
394+
"200": {
395+
"description": "User was locked",
396+
"content": {
397+
"application/json": {
398+
"schema": {
399+
"$ref": "#/components/schemas/SingleResponse_for_User"
400+
},
401+
"example": {
402+
"data": {
403+
"type": "user",
404+
"id": "030C1G60R30C1G60R30C1G60R3",
405+
"attributes": {
406+
"username": "charlie",
407+
"created_at": "1970-01-01T00:00:00Z",
408+
"locked_at": "1970-01-01T00:00:00Z",
409+
"can_request_admin": false
410+
},
411+
"links": {
412+
"self": "/api/admin/v1/users/030C1G60R30C1G60R30C1G60R3"
413+
}
414+
},
415+
"links": {
416+
"self": "/api/admin/v1/users/030C1G60R30C1G60R30C1G60R3/lock"
417+
}
418+
}
419+
}
420+
}
421+
},
422+
"404": {
423+
"description": "User ID not found",
424+
"content": {
425+
"application/json": {
426+
"schema": {
427+
"$ref": "#/components/schemas/ErrorResponse"
428+
},
429+
"example": {
430+
"errors": [
431+
{
432+
"title": "User ID 00000000000000000000000000 not found"
433+
}
434+
]
435+
}
436+
}
437+
}
438+
}
439+
}
440+
}
373441
}
374442
},
375443
"components": {

0 commit comments

Comments
 (0)