|
| 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 | +} |
0 commit comments