Reimplemented access and refresh tokens.

This commit is contained in:
2026-10-18 13:21:48 +02:00
parent 4343959c74
commit 26999d690f
28 changed files with 1510 additions and 480 deletions
+52 -83
View File
@@ -1,16 +1,13 @@
use axum::{extract::State, routing::post};
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use uuid::Uuid;
use crate::{
config::TokenConfig,
crypto::{generate_secret, hash_secret},
domain::{self, Token},
domain::{AccessToken, Secret},
error::AppError,
repository,
routes::{
dtos::token::{TokenRequest, TokenResponse, TokenRevocationRequest, TokenType},
dtos::token::{TokenRequest, TokenResponse, TokenRevocationRequest},
extractors::{Form, Json},
},
};
@@ -33,41 +30,57 @@ async fn issue_token(
client_id,
client_secret,
} => {
let token_pair = TokenPair::from_config(&token_config)?;
let secret_hash = hash_secret(&client_secret);
if !repository::user_app_secrets::verify(&pool, client_id, &secret_hash).await? {
let token_hash = Secret::from(client_secret).hash();
let (true, Some(app)) = (
repository::user_app_secrets::verify(&pool, client_id, &token_hash).await?,
repository::user_apps::get_by_id_unscoped(&pool, client_id).await?,
) else {
return Err(AppError::InvalidClientCredentials);
}
};
let app = repository::user_apps::get_by_id_unscoped(&pool, client_id)
.await?
.ok_or(AppError::InvalidClientCredentials)?;
let access_token = AccessToken::new(
app.user_id,
Some(app.id),
token_config.access_token_lifetime,
)?;
let token = token(&app, &token_pair);
repository::tokens::insert_access_token(&pool, access_token.clone().into()).await?;
repository::tokens::issue(&pool, token).await?;
Ok(Json(token_response(&token_pair, &token_config)))
Ok(Json(TokenResponse::new(access_token, None)))
}
TokenRequest::RefreshToken { refresh_token } => {
let token_pair = TokenPair::from_config(&token_config)?;
let old_refresh_token_hash = hash_secret(&refresh_token);
if !repository::tokens::rotate_refresh_token(
&pool,
&old_refresh_token_hash,
&token_pair.access_token_hash,
&token_pair.refresh_token_hash,
token_pair.access_expires_at,
token_pair.refresh_expires_at,
)
.await?
{
let token_hash = Secret::from(refresh_token).hash();
let (Some(access_token), Some(refresh_token)) = (
repository::tokens::get_access_token_by_refresh_hash(&pool, &token_hash).await?,
repository::tokens::get_refresh_token_by_hash(&pool, &token_hash).await?,
) else {
return Err(AppError::InvalidRefreshToken);
}
};
Ok(Json(token_response(&token_pair, &token_config)))
let new_access_token = access_token.refresh(token_config.access_token_lifetime)?;
repository::tokens::update_access_token_by_hash(
&pool,
&token_hash,
&new_access_token.secret.hash(),
new_access_token.expires_at,
new_access_token.issued_at,
)
.await?;
let new_refresh_token = refresh_token.refresh(token_config.refresh_token_lifetime)?;
repository::tokens::update_refresh_token_by_hash(
&pool,
&token_hash,
&new_refresh_token.secret.hash(),
new_refresh_token.expires_at,
new_refresh_token.issued_at,
)
.await?;
Ok(Json(TokenResponse::new(
new_access_token,
Some(new_refresh_token),
)))
}
}
}
@@ -78,58 +91,14 @@ async fn revoke_token(
State(pool): State<PgPool>,
Form(request): Form<TokenRevocationRequest>,
) -> Result<(), AppError> {
let token_hash = hash_secret(&request.token);
let token_hash = Secret::from(request.token).hash();
repository::tokens::revoke(&pool, &token_hash).await?;
repository::tokens::delete_access_token_by_hash(&pool, &token_hash)
.await
.ok();
repository::tokens::delete_refresh_token_by_hash(&pool, &token_hash)
.await
.ok();
Ok(())
}
struct TokenPair {
access_token: String,
refresh_token: String,
access_token_hash: Vec<u8>,
refresh_token_hash: Vec<u8>,
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
}
impl TokenPair {
fn from_config(token_config: &TokenConfig) -> Result<Self, AppError> {
let access_token = generate_secret().map_err(|_| AppError::Unknown)?;
let refresh_token = generate_secret().map_err(|_| AppError::Unknown)?;
let now = Utc::now();
Ok(TokenPair {
access_token_hash: hash_secret(&access_token),
refresh_token_hash: hash_secret(&refresh_token),
access_expires_at: now + token_config.access_token_lifetime,
refresh_expires_at: now + token_config.refresh_token_lifetime,
access_token,
refresh_token,
})
}
}
fn token(user_app: &domain::UserApp, generated: &TokenPair) -> Token {
Token {
id: Uuid::new_v4(),
user_id: user_app.user_id,
user_app_id: Some(user_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,
refreshed_at: None,
revoked_at: None,
created_at: Utc::now(),
}
}
fn token_response(generated: &TokenPair, token_config: &TokenConfig) -> TokenResponse {
TokenResponse {
access_token: generated.access_token.clone(),
token_type: TokenType::Bearer,
expires_in: token_config.access_token_lifetime.num_seconds(),
refresh_token: Some(generated.refresh_token.clone()),
}
}
+16
View File
@@ -1,6 +1,9 @@
use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::domain::{AccessToken, RefreshToken};
#[derive(Deserialize)]
#[serde(rename_all = "snake_case", tag = "grant_type")]
pub enum TokenRequest {
@@ -23,9 +26,22 @@ pub struct TokenResponse {
pub access_token: String,
pub token_type: TokenType,
pub expires_in: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
}
impl TokenResponse {
pub fn new(access_token: AccessToken, refresh_token: Option<RefreshToken>) -> Self {
Self {
access_token: access_token.secret.secret().to_string(),
token_type: TokenType::Bearer,
expires_in: (access_token.expires_at - Utc::now()).num_seconds(),
refresh_token: refresh_token.map(|r| r.secret.secret().to_string()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenType {
+8 -7
View File
@@ -61,13 +61,14 @@ impl ClientError for AppError {
impl ClientError for DomainError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
let message: String = match self {
Self::Amount(error) => error.to_string(),
Self::Schedule(error) => error.to_string(),
Self::UserAppSecret(error) => error.to_string(),
};
(StatusCode::UNPROCESSABLE_ENTITY, message.into())
match self {
Self::Amount(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into()),
Self::Secret(_) => internal_error(),
Self::Schedule(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into()),
Self::UserAppSecret(error) => {
(StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into())
}
}
}
}
+3 -3
View File
@@ -3,7 +3,7 @@ use sqlx::PgPool;
use super::{AuthScheme, Authorizer, Principal};
use crate::{
crypto::hash_secret,
domain::Secret,
repository::{self, RepositoryError},
};
@@ -32,8 +32,8 @@ where
) -> Result<Principal<Self>, Self::Error> {
let pool = PgPool::from_ref(state);
let token_hash = hash_secret(&credentials.0);
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
let token_hash = Secret::from(credentials.0).hash();
let token = repository::tokens::get_access_token_by_hash(&pool, &token_hash)
.await
.map_err(BearerError::Repository)?
.ok_or(BearerError::InvalidCredentials)?;