Added user apps and token resources.
This commit is contained in:
@@ -1,7 +1,21 @@
|
||||
use axum::routing::post;
|
||||
use axum::{extract::State, routing::post};
|
||||
use chrono::{Duration, Utc};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::{
|
||||
crypto::{generate_secret, hash_secret},
|
||||
domain::Token,
|
||||
error::AppError,
|
||||
repository::{self, user_app_secrets},
|
||||
routes::{
|
||||
dtos::token::{TokenRequest, TokenResponse, TokenRevocationRequest, TokenType},
|
||||
extractors::{form::Form, json::Json},
|
||||
},
|
||||
};
|
||||
|
||||
const ACCESS_TOKEN_LIFETIME_SECONDS: i64 = 3600;
|
||||
const REFRESH_TOKEN_LIFETIME_SECONDS: i64 = 30 * 24 * 60 * 60;
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new()
|
||||
@@ -10,13 +24,110 @@ pub fn create_router() -> axum::Router<PgPool> {
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument()]
|
||||
async fn issue_token() -> Result<(), AppError> {
|
||||
Ok(())
|
||||
#[tracing::instrument(skip(pool, token_request))]
|
||||
async fn issue_token(
|
||||
State(pool): State<PgPool>,
|
||||
Form(token_request): Form<TokenRequest>,
|
||||
) -> Result<Json<TokenResponse>, AppError> {
|
||||
match token_request {
|
||||
TokenRequest::ClientCredentials {
|
||||
client_id,
|
||||
client_secret,
|
||||
} => {
|
||||
let secret_hash = hash_secret(&client_secret);
|
||||
if !user_app_secrets::verify(&pool, client_id, &secret_hash).await? {
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
|
||||
let generated = generate_token_pair()?;
|
||||
repository::tokens::issue(&pool, token(client_id, &generated)).await?;
|
||||
|
||||
Ok(Json(token_response(
|
||||
generated.access_token,
|
||||
generated.refresh_token,
|
||||
)))
|
||||
}
|
||||
TokenRequest::RefreshToken { refresh_token } => {
|
||||
let generated = generate_token_pair()?;
|
||||
let old_refresh_hash = hash_secret(&refresh_token);
|
||||
let mut tx = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(repository::RepositoryError::from)?;
|
||||
let rotated = repository::tokens::rotate_refresh_token(
|
||||
&mut *tx,
|
||||
&old_refresh_hash,
|
||||
&generated.access_token_hash,
|
||||
&generated.refresh_token_hash,
|
||||
generated.access_expires_at,
|
||||
generated.refresh_expires_at,
|
||||
)
|
||||
.await?;
|
||||
if !rotated {
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(repository::RepositoryError::from)?;
|
||||
|
||||
Ok(Json(token_response(
|
||||
generated.access_token,
|
||||
generated.refresh_token,
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument()]
|
||||
async fn revoke_token() -> Result<(), AppError> {
|
||||
Ok(())
|
||||
#[tracing::instrument(skip(pool, request))]
|
||||
async fn revoke_token(
|
||||
State(pool): State<PgPool>,
|
||||
Form(request): Form<TokenRevocationRequest>,
|
||||
) -> Result<(), AppError> {
|
||||
Ok(repository::tokens::revoke(&pool, &hash_secret(&request.token)).await?)
|
||||
}
|
||||
|
||||
struct GeneratedTokenPair {
|
||||
access_token: String,
|
||||
refresh_token: String,
|
||||
access_token_hash: Vec<u8>,
|
||||
refresh_token_hash: Vec<u8>,
|
||||
access_expires_at: chrono::DateTime<Utc>,
|
||||
refresh_expires_at: chrono::DateTime<Utc>,
|
||||
}
|
||||
|
||||
fn generate_token_pair() -> Result<GeneratedTokenPair, AppError> {
|
||||
let access_token = generate_secret().map_err(|_| AppError::Internal)?;
|
||||
let refresh_token = generate_secret().map_err(|_| AppError::Internal)?;
|
||||
let now = Utc::now();
|
||||
Ok(GeneratedTokenPair {
|
||||
access_token_hash: hash_secret(&access_token),
|
||||
refresh_token_hash: hash_secret(&refresh_token),
|
||||
access_expires_at: now + Duration::seconds(ACCESS_TOKEN_LIFETIME_SECONDS),
|
||||
refresh_expires_at: now + Duration::seconds(REFRESH_TOKEN_LIFETIME_SECONDS),
|
||||
access_token,
|
||||
refresh_token,
|
||||
})
|
||||
}
|
||||
|
||||
fn token(app_id: Uuid, generated: &GeneratedTokenPair) -> Token {
|
||||
Token {
|
||||
id: Uuid::new_v4(),
|
||||
app_id,
|
||||
access_token_hash: generated.access_token_hash.clone(),
|
||||
refresh_token_hash: generated.refresh_token_hash.clone(),
|
||||
access_expires_at: generated.access_expires_at,
|
||||
refresh_expires_at: generated.refresh_expires_at,
|
||||
revoked_at: None,
|
||||
created_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn token_response(access_token: String, refresh_token: String) -> TokenResponse {
|
||||
TokenResponse {
|
||||
access_token,
|
||||
token_type: TokenType::Bearer,
|
||||
expires_in: ACCESS_TOKEN_LIFETIME_SECONDS,
|
||||
refresh_token: Some(refresh_token),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
pub mod account;
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod token;
|
||||
pub mod transaction;
|
||||
pub mod user;
|
||||
pub mod user_app;
|
||||
pub mod user_app_secret;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "grant_type")]
|
||||
pub enum TokenRequest {
|
||||
ClientCredentials {
|
||||
client_id: Uuid,
|
||||
client_secret: String,
|
||||
},
|
||||
RefreshToken {
|
||||
refresh_token: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenRevocationRequest {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct TokenResponse {
|
||||
pub access_token: String,
|
||||
pub token_type: TokenType,
|
||||
pub expires_in: i64,
|
||||
pub refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TokenType {
|
||||
Bearer,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serializes_token_response() {
|
||||
let response = TokenResponse {
|
||||
access_token: "access-token".to_string(),
|
||||
token_type: TokenType::Bearer,
|
||||
expires_in: 3600,
|
||||
refresh_token: Some("refresh-token".to_string()),
|
||||
};
|
||||
let value = serde_json::to_value(response).unwrap();
|
||||
|
||||
assert_eq!(value["access_token"], "access-token");
|
||||
assert_eq!(value["token_type"], "bearer");
|
||||
assert_eq!(value["expires_in"], 3600);
|
||||
assert_eq!(value["refresh_token"], "refresh-token");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UserAppRequest {}
|
||||
|
||||
impl UserAppRequest {
|
||||
pub fn into_domain(self, user_id: Uuid, id: Uuid) -> domain::UserApp {
|
||||
domain::UserApp { id, user_id }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UserAppResponse {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
impl From<domain::UserApp> for UserAppResponse {
|
||||
fn from(app: domain::UserApp) -> Self {
|
||||
Self { id: app.id }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serializes_user_app_response() {
|
||||
let id = Uuid::new_v4();
|
||||
let response = UserAppResponse::from(domain::UserApp {
|
||||
id,
|
||||
user_id: Uuid::new_v4(),
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(response).unwrap()["id"],
|
||||
id.to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_empty_put_payload() {
|
||||
let request: UserAppRequest = serde_json::from_str("{}").unwrap();
|
||||
let user_id = Uuid::new_v4();
|
||||
let id = Uuid::new_v4();
|
||||
let app = request.into_domain(user_id, id);
|
||||
|
||||
assert_eq!(app, domain::UserApp { id, user_id });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use chrono::{DateTime, FixedOffset, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UserAppSecretRequest {
|
||||
pub expires_at: DateTime<FixedOffset>,
|
||||
}
|
||||
|
||||
impl UserAppSecretRequest {
|
||||
pub fn expires_at_utc(&self) -> DateTime<Utc> {
|
||||
self.expires_at.with_timezone(&Utc)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UserAppSecretResponse {
|
||||
pub id: Uuid,
|
||||
pub app_id: Uuid,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<domain::UserAppSecret> for UserAppSecretResponse {
|
||||
fn from(secret: domain::UserAppSecret) -> Self {
|
||||
Self {
|
||||
id: secret.id,
|
||||
app_id: secret.app_id,
|
||||
expires_at: secret.expires_at,
|
||||
created_at: secret.created_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CreatedUserAppSecretResponse {
|
||||
#[serde(flatten)]
|
||||
pub credential: UserAppSecretResponse,
|
||||
pub secret: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_timezone_aware_expiration() {
|
||||
let request: UserAppSecretRequest =
|
||||
serde_json::from_str(r#"{"expires_at":"2030-01-01T12:00:00+02:00"}"#).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
request.expires_at_utc().to_rfc3339(),
|
||||
"2030-01-01T10:00:00+00:00"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_expiration_without_timezone() {
|
||||
assert!(
|
||||
serde_json::from_str::<UserAppSecretRequest>(r#"{"expires_at":"2030-01-01T12:00:00"}"#)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_response_does_not_expose_secret_hash() {
|
||||
let response = UserAppSecretResponse {
|
||||
id: Uuid::new_v4(),
|
||||
app_id: Uuid::new_v4(),
|
||||
expires_at: Utc::now(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
let value = serde_json::to_value(response).unwrap();
|
||||
|
||||
assert!(value.get("secret").is_none());
|
||||
assert!(value.get("secret_hash").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod form;
|
||||
pub mod json;
|
||||
pub mod path;
|
||||
pub mod query;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
use axum::extract::{FromRequest, Request};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
pub struct Form<T>(pub T);
|
||||
|
||||
impl<T, S> FromRequest<S> for Form<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
|
||||
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
axum::Form::<T>::from_request(request, state)
|
||||
.await
|
||||
.map(|axum::Form(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
dtos::user_app_secret::{
|
||||
CreatedUserAppSecretResponse, UserAppSecretRequest, UserAppSecretResponse,
|
||||
},
|
||||
extractors::{json::Json, path::Path, query::Query},
|
||||
};
|
||||
use crate::{
|
||||
crypto::{generate_secret, hash_secret},
|
||||
domain::UserAppSecret,
|
||||
error::AppError,
|
||||
repository::{
|
||||
dtos::{Delete, Upsert},
|
||||
user_app_secrets as repository,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new()
|
||||
.route("/", axum::routing::get(list_user_app_secrets))
|
||||
.route(
|
||||
"/{secret_id}",
|
||||
axum::routing::get(get_user_app_secret)
|
||||
.put(upsert_user_app_secret)
|
||||
.delete(delete_user_app_secret),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct QueryParams {
|
||||
pub limit: Option<u64>,
|
||||
pub offset: Option<u64>,
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn list_user_app_secrets(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<UserAppSecretResponse>>, AppError> {
|
||||
let secrets = repository::list(
|
||||
&pool,
|
||||
repository::Query {
|
||||
app_id,
|
||||
limit: Some(query.limit.unwrap_or(20)),
|
||||
offset: query.offset,
|
||||
},
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(UserAppSecretResponse::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(secrets))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_user_app_secret(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id, secret_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
) -> Result<Json<UserAppSecretResponse>, AppError> {
|
||||
let secret = repository::get(&pool, app_id, secret_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(secret.into()))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool, request))]
|
||||
async fn upsert_user_app_secret(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id, secret_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Json(request): Json<UserAppSecretRequest>,
|
||||
) -> Result<(StatusCode, Json<CreatedUserAppSecretResponse>), AppError> {
|
||||
let expires_at = request.expires_at_utc();
|
||||
if expires_at <= chrono::Utc::now() {
|
||||
return Err(AppError::BadRequest(
|
||||
"expires_at must be in the future".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
let generated_secret = generate_secret().map_err(|_| AppError::Internal)?;
|
||||
let secret = UserAppSecret {
|
||||
id: secret_id,
|
||||
app_id,
|
||||
secret_hash: hash_secret(&generated_secret),
|
||||
expires_at,
|
||||
created_at: chrono::Utc::now(),
|
||||
};
|
||||
let upsert = repository::upsert(&pool, secret).await?;
|
||||
|
||||
let (status, secret) = match upsert {
|
||||
Upsert::Created(secret) => (StatusCode::CREATED, secret),
|
||||
Upsert::Updated(secret) => (StatusCode::OK, secret),
|
||||
};
|
||||
|
||||
Ok((
|
||||
status,
|
||||
Json(CreatedUserAppSecretResponse {
|
||||
credential: secret.into(),
|
||||
secret: generated_secret,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn delete_user_app_secret(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id, secret_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::delete(&pool, app_id, secret_id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
dtos::user_app::{UserAppRequest, UserAppResponse},
|
||||
extractors::{json::Json, path::Path, query::Query},
|
||||
};
|
||||
use crate::{
|
||||
error::AppError,
|
||||
repository::{
|
||||
dtos::{Delete, Upsert},
|
||||
user_apps as repository,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new()
|
||||
.route("/", axum::routing::get(list_user_apps))
|
||||
.route(
|
||||
"/{app_id}",
|
||||
axum::routing::get(get_user_app)
|
||||
.put(upsert_user_app)
|
||||
.delete(delete_user_app),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct QueryParams {
|
||||
pub limit: Option<u64>,
|
||||
pub offset: Option<u64>,
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn list_user_apps(
|
||||
State(pool): State<PgPool>,
|
||||
Path(user_id): Path<Uuid>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<UserAppResponse>>, AppError> {
|
||||
let apps = repository::list(
|
||||
&pool,
|
||||
repository::Query {
|
||||
user_id,
|
||||
limit: Some(query.limit.unwrap_or(20)),
|
||||
offset: query.offset,
|
||||
},
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(UserAppResponse::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(apps))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_user_app(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Json<UserAppResponse>, AppError> {
|
||||
let app = repository::get(&pool, user_id, app_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(app.into()))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool, request))]
|
||||
async fn upsert_user_app(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
|
||||
Json(request): Json<UserAppRequest>,
|
||||
) -> Result<(StatusCode, Json<UserAppResponse>), AppError> {
|
||||
let app = request.into_domain(user_id, app_id);
|
||||
let upsert = repository::upsert(&pool, app).await?;
|
||||
|
||||
let (status, app) = match upsert {
|
||||
Upsert::Created(app) => (StatusCode::CREATED, app),
|
||||
Upsert::Updated(app) => (StatusCode::OK, app),
|
||||
};
|
||||
|
||||
Ok((status, Json(app.into())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn delete_user_app(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::delete(&pool, user_id, app_id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user