Skip to content

Commit 6000719

Browse files
committed
Admin API to get individual user registration tokens
1 parent 322c854 commit 6000719

File tree

4 files changed

+270
-1
lines changed

4 files changed

+270
-1
lines changed

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,13 @@ where
127127
self::user_registration_tokens::list_doc,
128128
),
129129
)
130+
.api_route(
131+
"/user-registration-tokens/{id}",
132+
get_with(
133+
self::user_registration_tokens::get,
134+
self::user_registration_tokens::get_doc,
135+
),
136+
)
130137
.api_route(
131138
"/upstream-oauth-links",
132139
get_with(
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
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::{OperationIo, transform::TransformOperation};
7+
use axum::{Json, response::IntoResponse};
8+
use hyper::StatusCode;
9+
use mas_axum_utils::record_error;
10+
use ulid::Ulid;
11+
12+
use crate::{
13+
admin::{
14+
call_context::CallContext,
15+
model::UserRegistrationToken,
16+
params::UlidPathParam,
17+
response::{ErrorResponse, SingleResponse},
18+
},
19+
impl_from_error_for_route,
20+
};
21+
22+
#[derive(Debug, thiserror::Error, OperationIo)]
23+
#[aide(output_with = "Json<ErrorResponse>")]
24+
pub enum RouteError {
25+
#[error(transparent)]
26+
Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
27+
28+
#[error("Registration token with ID {0} not found")]
29+
NotFound(Ulid),
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+
Self::NotFound(_) => StatusCode::NOT_FOUND,
41+
};
42+
(status, sentry_event_id, Json(error)).into_response()
43+
}
44+
}
45+
46+
pub fn doc(operation: TransformOperation) -> TransformOperation {
47+
operation
48+
.id("getUserRegistrationToken")
49+
.summary("Get a user registration token")
50+
.tag("user-registration-token")
51+
.response_with::<200, Json<SingleResponse<UserRegistrationToken>>, _>(|t| {
52+
let [sample, ..] = UserRegistrationToken::samples();
53+
let response = SingleResponse::new_canonical(sample);
54+
t.description("Registration token was found")
55+
.example(response)
56+
})
57+
.response_with::<404, RouteError, _>(|t| {
58+
let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
59+
t.description("Registration token was not found")
60+
.example(response)
61+
})
62+
}
63+
64+
#[tracing::instrument(name = "handler.admin.v1.user_registration_tokens.get", skip_all)]
65+
pub async fn handler(
66+
CallContext { mut repo, .. }: CallContext,
67+
id: UlidPathParam,
68+
) -> Result<Json<SingleResponse<UserRegistrationToken>>, RouteError> {
69+
let token = repo
70+
.user_registration_token()
71+
.lookup(*id)
72+
.await?
73+
.ok_or(RouteError::NotFound(*id))?;
74+
75+
Ok(Json(SingleResponse::new_canonical(
76+
UserRegistrationToken::from(token),
77+
)))
78+
}
79+
80+
#[cfg(test)]
81+
mod tests {
82+
use hyper::{Request, StatusCode};
83+
use insta::assert_json_snapshot;
84+
use sqlx::PgPool;
85+
use ulid::Ulid;
86+
87+
use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup};
88+
89+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
90+
async fn test_get_token(pool: PgPool) {
91+
setup();
92+
let mut state = TestState::from_pool(pool).await.unwrap();
93+
let token = state.token_with_scope("urn:mas:admin").await;
94+
95+
let mut repo = state.repository().await.unwrap();
96+
let registration_token = repo
97+
.user_registration_token()
98+
.add(
99+
&mut state.rng(),
100+
&state.clock,
101+
"test_token_123".to_owned(),
102+
Some(5),
103+
None,
104+
)
105+
.await
106+
.unwrap();
107+
repo.save().await.unwrap();
108+
109+
let request = Request::get(format!(
110+
"/api/admin/v1/user-registration-tokens/{}",
111+
registration_token.id
112+
))
113+
.bearer(&token)
114+
.empty();
115+
let response = state.request(request).await;
116+
response.assert_status(StatusCode::OK);
117+
let body: serde_json::Value = response.json();
118+
119+
assert_json_snapshot!(body, @r###"
120+
{
121+
"data": {
122+
"type": "user-registration_token",
123+
"id": "01FSHN9AG0MZAA6S4AF7CTV32E",
124+
"attributes": {
125+
"token": "test_token_123",
126+
"usage_limit": 5,
127+
"times_used": 0,
128+
"created_at": "2022-01-16T14:40:00Z",
129+
"last_used_at": null,
130+
"expires_at": null,
131+
"revoked_at": null
132+
},
133+
"links": {
134+
"self": "/api/admin/v1/user-registration-tokens/01FSHN9AG0MZAA6S4AF7CTV32E"
135+
}
136+
},
137+
"links": {
138+
"self": "/api/admin/v1/user-registration-tokens/01FSHN9AG0MZAA6S4AF7CTV32E"
139+
}
140+
}
141+
"###);
142+
}
143+
144+
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
145+
async fn test_get_nonexistent_token(pool: PgPool) {
146+
setup();
147+
let mut state = TestState::from_pool(pool).await.unwrap();
148+
let token = state.token_with_scope("urn:mas:admin").await;
149+
150+
// Use a fixed ID for the test to ensure consistent snapshots
151+
let nonexistent_id = Ulid::from_string("00000000000000000000000000").unwrap();
152+
let request = Request::get(format!(
153+
"/api/admin/v1/user-registration-tokens/{nonexistent_id}"
154+
))
155+
.bearer(&token)
156+
.empty();
157+
let response = state.request(request).await;
158+
response.assert_status(StatusCode::NOT_FOUND);
159+
let body: serde_json::Value = response.json();
160+
161+
assert_json_snapshot!(body, @r###"
162+
{
163+
"errors": [
164+
{
165+
"title": "Registration token with ID 00000000000000000000000000 not found"
166+
}
167+
]
168+
}
169+
"###);
170+
}
171+
}

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

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

6+
mod get;
67
mod list;
78

8-
pub use self::list::{doc as list_doc, handler as list};
9+
pub use self::{
10+
get::{doc as get_doc, handler as get},
11+
list::{doc as list_doc, handler as list},
12+
};

docs/api/spec.json

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2292,6 +2292,77 @@
22922292
}
22932293
}
22942294
},
2295+
"/api/admin/v1/user-registration-tokens/{id}": {
2296+
"get": {
2297+
"tags": [
2298+
"user-registration-token"
2299+
],
2300+
"summary": "Get a user registration token",
2301+
"operationId": "getUserRegistrationToken",
2302+
"parameters": [
2303+
{
2304+
"in": "path",
2305+
"name": "id",
2306+
"required": true,
2307+
"schema": {
2308+
"title": "The ID of the resource",
2309+
"$ref": "#/components/schemas/ULID"
2310+
},
2311+
"style": "simple"
2312+
}
2313+
],
2314+
"responses": {
2315+
"200": {
2316+
"description": "Registration token was found",
2317+
"content": {
2318+
"application/json": {
2319+
"schema": {
2320+
"$ref": "#/components/schemas/SingleResponse_for_UserRegistrationToken"
2321+
},
2322+
"example": {
2323+
"data": {
2324+
"type": "user-registration_token",
2325+
"id": "01040G2081040G2081040G2081",
2326+
"attributes": {
2327+
"token": "abc123def456",
2328+
"usage_limit": 10,
2329+
"times_used": 5,
2330+
"created_at": "1970-01-01T00:00:00Z",
2331+
"last_used_at": "1970-01-01T00:00:00Z",
2332+
"expires_at": "1970-01-31T00:00:00Z",
2333+
"revoked_at": null
2334+
},
2335+
"links": {
2336+
"self": "/api/admin/v1/user-registration-tokens/01040G2081040G2081040G2081"
2337+
}
2338+
},
2339+
"links": {
2340+
"self": "/api/admin/v1/user-registration-tokens/01040G2081040G2081040G2081"
2341+
}
2342+
}
2343+
}
2344+
}
2345+
},
2346+
"404": {
2347+
"description": "Registration token was not found",
2348+
"content": {
2349+
"application/json": {
2350+
"schema": {
2351+
"$ref": "#/components/schemas/ErrorResponse"
2352+
},
2353+
"example": {
2354+
"errors": [
2355+
{
2356+
"title": "Registration token with ID 00000000000000000000000000 not found"
2357+
}
2358+
]
2359+
}
2360+
}
2361+
}
2362+
}
2363+
}
2364+
}
2365+
},
22952366
"/api/admin/v1/upstream-oauth-links": {
22962367
"get": {
22972368
"tags": [
@@ -3878,6 +3949,22 @@
38783949
}
38793950
}
38803951
},
3952+
"SingleResponse_for_UserRegistrationToken": {
3953+
"description": "A top-level response with a single resource",
3954+
"type": "object",
3955+
"required": [
3956+
"data",
3957+
"links"
3958+
],
3959+
"properties": {
3960+
"data": {
3961+
"$ref": "#/components/schemas/SingleResource_for_UserRegistrationToken"
3962+
},
3963+
"links": {
3964+
"$ref": "#/components/schemas/SelfLinks"
3965+
}
3966+
}
3967+
},
38813968
"UpstreamOAuthLinkFilter": {
38823969
"type": "object",
38833970
"properties": {

0 commit comments

Comments
 (0)