Skip to content

Commit aa7c6b3

Browse files
committed
Admin API to create a new user registration token
1 parent 6000719 commit aa7c6b3

File tree

4 files changed

+278
-0
lines changed

4 files changed

+278
-0
lines changed

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,10 @@ where
125125
get_with(
126126
self::user_registration_tokens::list,
127127
self::user_registration_tokens::list_doc,
128+
)
129+
.post_with(
130+
self::user_registration_tokens::add,
131+
self::user_registration_tokens::add_doc,
128132
),
129133
)
130134
.api_route(
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
// Copyright 2025 The Matrix.org Foundation C.I.C.
2+
//
3+
// SPDX-License-Identifier: AGPL-3.0-only
4+
// Please see LICENSE in the repository root for full details.
5+
6+
use aide::{NoApi, OperationIo, transform::TransformOperation};
7+
use axum::{Json, response::IntoResponse};
8+
use chrono::{DateTime, Utc};
9+
use hyper::StatusCode;
10+
use mas_axum_utils::record_error;
11+
use mas_storage::BoxRng;
12+
use rand::{Rng, distributions::Alphanumeric};
13+
use schemars::JsonSchema;
14+
use serde::Deserialize;
15+
16+
use crate::{
17+
admin::{
18+
call_context::CallContext,
19+
model::UserRegistrationToken,
20+
response::{ErrorResponse, SingleResponse},
21+
},
22+
impl_from_error_for_route,
23+
};
24+
25+
#[derive(Debug, thiserror::Error, OperationIo)]
26+
#[aide(output_with = "Json<ErrorResponse>")]
27+
pub enum RouteError {
28+
#[error(transparent)]
29+
Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
30+
}
31+
32+
impl_from_error_for_route!(mas_storage::RepositoryError);
33+
34+
impl IntoResponse for RouteError {
35+
fn into_response(self) -> axum::response::Response {
36+
let error = ErrorResponse::from_error(&self);
37+
let sentry_event_id = record_error!(self, Self::Internal(_));
38+
let status = match self {
39+
Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
40+
};
41+
(status, sentry_event_id, Json(error)).into_response()
42+
}
43+
}
44+
45+
/// # JSON payload for the `POST /api/admin/v1/user-registration-tokens`
46+
#[derive(Deserialize, JsonSchema)]
47+
#[serde(rename = "AddUserRegistrationTokenRequest")]
48+
pub struct Request {
49+
/// The token string. If not provided, a random token will be generated.
50+
token: Option<String>,
51+
52+
/// Maximum number of times this token can be used. If not provided, the
53+
/// token can be used an unlimited number of times.
54+
usage_limit: Option<u32>,
55+
56+
/// When the token expires. If not provided, the token never expires.
57+
expires_at: Option<DateTime<Utc>>,
58+
}
59+
60+
pub fn doc(operation: TransformOperation) -> TransformOperation {
61+
operation
62+
.id("addUserRegistrationToken")
63+
.summary("Create a new user registration token")
64+
.tag("user-registration-token")
65+
.response_with::<201, Json<SingleResponse<UserRegistrationToken>>, _>(|t| {
66+
let [sample, ..] = UserRegistrationToken::samples();
67+
let response = SingleResponse::new_canonical(sample);
68+
t.description("A new user registration token was created")
69+
.example(response)
70+
})
71+
}
72+
73+
#[tracing::instrument(name = "handler.admin.v1.user_registration_tokens.post", skip_all)]
74+
pub async fn handler(
75+
CallContext {
76+
mut repo, clock, ..
77+
}: CallContext,
78+
NoApi(mut rng): NoApi<BoxRng>,
79+
Json(params): Json<Request>,
80+
) -> Result<(StatusCode, Json<SingleResponse<UserRegistrationToken>>), RouteError> {
81+
// Generate a random token if none was provided
82+
let token = params.token.unwrap_or_else(|| {
83+
(&mut rng)
84+
.sample_iter(&Alphanumeric)
85+
.take(12)
86+
.map(char::from)
87+
.collect()
88+
});
89+
90+
let registration_token = repo
91+
.user_registration_token()
92+
.add(
93+
&mut rng,
94+
&clock,
95+
token,
96+
params.usage_limit,
97+
params.expires_at,
98+
)
99+
.await?;
100+
101+
repo.save().await?;
102+
103+
Ok((
104+
StatusCode::CREATED,
105+
Json(SingleResponse::new_canonical(registration_token.into())),
106+
))
107+
}
108+
109+
#[cfg(test)]
110+
mod tests {
111+
use hyper::{Request, StatusCode};
112+
use insta::assert_json_snapshot;
113+
use sqlx::PgPool;
114+
115+
use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup};
116+
117+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
118+
async fn test_create(pool: PgPool) {
119+
setup();
120+
let mut state = TestState::from_pool(pool).await.unwrap();
121+
let token = state.token_with_scope("urn:mas:admin").await;
122+
123+
let request = Request::post("/api/admin/v1/user-registration-tokens")
124+
.bearer(&token)
125+
.json(serde_json::json!({
126+
"token": "test_token_123",
127+
"usage_limit": 5,
128+
}));
129+
let response = state.request(request).await;
130+
response.assert_status(StatusCode::CREATED);
131+
let body: serde_json::Value = response.json();
132+
133+
assert_json_snapshot!(body, @r#"
134+
{
135+
"data": {
136+
"type": "user-registration_token",
137+
"id": "01FSHN9AG0MZAA6S4AF7CTV32E",
138+
"attributes": {
139+
"token": "test_token_123",
140+
"usage_limit": 5,
141+
"times_used": 0,
142+
"created_at": "2022-01-16T14:40:00Z",
143+
"last_used_at": null,
144+
"expires_at": null,
145+
"revoked_at": null
146+
},
147+
"links": {
148+
"self": "/api/admin/v1/user-registration-tokens/01FSHN9AG0MZAA6S4AF7CTV32E"
149+
}
150+
},
151+
"links": {
152+
"self": "/api/admin/v1/user-registration-tokens/01FSHN9AG0MZAA6S4AF7CTV32E"
153+
}
154+
}
155+
"#);
156+
}
157+
158+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
159+
async fn test_create_auto_token(pool: PgPool) {
160+
setup();
161+
let mut state = TestState::from_pool(pool).await.unwrap();
162+
let token = state.token_with_scope("urn:mas:admin").await;
163+
164+
let request = Request::post("/api/admin/v1/user-registration-tokens")
165+
.bearer(&token)
166+
.json(serde_json::json!({
167+
"usage_limit": 1
168+
}));
169+
let response = state.request(request).await;
170+
response.assert_status(StatusCode::CREATED);
171+
172+
let body: serde_json::Value = response.json();
173+
174+
assert_json_snapshot!(body, @r#"
175+
{
176+
"data": {
177+
"type": "user-registration_token",
178+
"id": "01FSHN9AG0QMGC989M0XSFVF2X",
179+
"attributes": {
180+
"token": "42oTpLoieH5I",
181+
"usage_limit": 1,
182+
"times_used": 0,
183+
"created_at": "2022-01-16T14:40:00Z",
184+
"last_used_at": null,
185+
"expires_at": null,
186+
"revoked_at": null
187+
},
188+
"links": {
189+
"self": "/api/admin/v1/user-registration-tokens/01FSHN9AG0QMGC989M0XSFVF2X"
190+
}
191+
},
192+
"links": {
193+
"self": "/api/admin/v1/user-registration-tokens/01FSHN9AG0QMGC989M0XSFVF2X"
194+
}
195+
}
196+
"#);
197+
}
198+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
// SPDX-License-Identifier: AGPL-3.0-only
44
// Please see LICENSE in the repository root for full details.
55

6+
mod add;
67
mod get;
78
mod list;
89

910
pub use self::{
11+
add::{doc as add_doc, handler as add},
1012
get::{doc as get_doc, handler as get},
1113
list::{doc as list_doc, handler as list},
1214
};

docs/api/spec.json

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2290,6 +2290,56 @@
22902290
}
22912291
}
22922292
}
2293+
},
2294+
"post": {
2295+
"tags": [
2296+
"user-registration-token"
2297+
],
2298+
"summary": "Create a new user registration token",
2299+
"operationId": "addUserRegistrationToken",
2300+
"requestBody": {
2301+
"content": {
2302+
"application/json": {
2303+
"schema": {
2304+
"$ref": "#/components/schemas/AddUserRegistrationTokenRequest"
2305+
}
2306+
}
2307+
},
2308+
"required": true
2309+
},
2310+
"responses": {
2311+
"201": {
2312+
"description": "A new user registration token was created",
2313+
"content": {
2314+
"application/json": {
2315+
"schema": {
2316+
"$ref": "#/components/schemas/SingleResponse_for_UserRegistrationToken"
2317+
},
2318+
"example": {
2319+
"data": {
2320+
"type": "user-registration_token",
2321+
"id": "01040G2081040G2081040G2081",
2322+
"attributes": {
2323+
"token": "abc123def456",
2324+
"usage_limit": 10,
2325+
"times_used": 5,
2326+
"created_at": "1970-01-01T00:00:00Z",
2327+
"last_used_at": "1970-01-01T00:00:00Z",
2328+
"expires_at": "1970-01-31T00:00:00Z",
2329+
"revoked_at": null
2330+
},
2331+
"links": {
2332+
"self": "/api/admin/v1/user-registration-tokens/01040G2081040G2081040G2081"
2333+
}
2334+
},
2335+
"links": {
2336+
"self": "/api/admin/v1/user-registration-tokens/01040G2081040G2081040G2081"
2337+
}
2338+
}
2339+
}
2340+
}
2341+
}
2342+
}
22932343
}
22942344
},
22952345
"/api/admin/v1/user-registration-tokens/{id}": {
@@ -3949,6 +3999,30 @@
39493999
}
39504000
}
39514001
},
4002+
"AddUserRegistrationTokenRequest": {
4003+
"title": "JSON payload for the `POST /api/admin/v1/user-registration-tokens`",
4004+
"type": "object",
4005+
"properties": {
4006+
"token": {
4007+
"description": "The token string. If not provided, a random token will be generated.",
4008+
"type": "string",
4009+
"nullable": true
4010+
},
4011+
"usage_limit": {
4012+
"description": "Maximum number of times this token can be used. If not provided, the token can be used an unlimited number of times.",
4013+
"type": "integer",
4014+
"format": "uint32",
4015+
"minimum": 0.0,
4016+
"nullable": true
4017+
},
4018+
"expires_at": {
4019+
"description": "When the token expires. If not provided, the token never expires.",
4020+
"type": "string",
4021+
"format": "date-time",
4022+
"nullable": true
4023+
}
4024+
}
4025+
},
39524026
"SingleResponse_for_UserRegistrationToken": {
39534027
"description": "A top-level response with a single resource",
39544028
"type": "object",

0 commit comments

Comments
 (0)