Configure tokens (and other components) through Config structs.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
use chrono::Duration;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerConfig {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
impl ServerConfig {
|
||||
pub fn load_from_env() -> Self {
|
||||
let host = std::env::var("HOST").expect("HOST must be set");
|
||||
let port = std::env::var("PORT")
|
||||
.expect("PORT must be set")
|
||||
.parse()
|
||||
.expect("PORT must be a valid u16");
|
||||
Self { host, port }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DatabaseConfig {
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
impl DatabaseConfig {
|
||||
pub fn load_from_env() -> Self {
|
||||
let url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
Self { url }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TokenConfig {
|
||||
pub access_token_lifetime: Duration,
|
||||
pub refresh_token_lifetime: Duration,
|
||||
}
|
||||
|
||||
impl TokenConfig {
|
||||
pub fn load_from_env() -> Self {
|
||||
let access_token_lifetime_secs = std::env::var("ACCESS_TOKEN_LIFETIME_SECONDS")
|
||||
.expect("ACCESS_TOKEN_LIFETIME_SECONDS must be set")
|
||||
.parse::<u64>()
|
||||
.expect("ACCESS_TOKEN_LIFETIME_SECONDS must be a valid u64");
|
||||
let refresh_token_lifetime_secs = std::env::var("REFRESH_TOKEN_LIFETIME_SECONDS")
|
||||
.expect("REFRESH_TOKEN_LIFETIME_SECONDS must be set")
|
||||
.parse::<u64>()
|
||||
.expect("REFRESH_TOKEN_LIFETIME_SECONDS must be a valid u64");
|
||||
Self {
|
||||
access_token_lifetime: Duration::seconds(access_token_lifetime_secs as i64),
|
||||
refresh_token_lifetime: Duration::seconds(refresh_token_lifetime_secs as i64),
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -1,9 +1,8 @@
|
||||
use std::env;
|
||||
|
||||
use anyhow::Context;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
mod config;
|
||||
mod crypto;
|
||||
mod database;
|
||||
mod domain;
|
||||
@@ -21,35 +20,36 @@ async fn main() -> anyhow::Result<()> {
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
let database_url = env::var("DATABASE_URL").context("DATABASE_URL must be set")?;
|
||||
let pool = PgPoolOptions::new()
|
||||
let db_config = config::DatabaseConfig::load_from_env();
|
||||
let db_pool = PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(&database_url)
|
||||
.connect(&db_config.url)
|
||||
.await
|
||||
.context("failed to connect to database")?;
|
||||
|
||||
sqlx::migrate!()
|
||||
.run(&pool)
|
||||
.run(&db_pool)
|
||||
.await
|
||||
.context("failed to run database migrations")?;
|
||||
|
||||
let state = state::AppState::new(pool.clone());
|
||||
let router = routes::create_router(state);
|
||||
let token_config = config::TokenConfig::load_from_env();
|
||||
|
||||
let host = env::var("HOST").context("HOST must be set")?;
|
||||
let port = env::var("PORT").context("PORT must be set")?;
|
||||
let addr = format!("{}:{}", host, port);
|
||||
let listener = TcpListener::bind(&addr)
|
||||
let app_state = state::AppState::new(db_pool.clone(), token_config);
|
||||
let app_router = routes::create_router(app_state);
|
||||
|
||||
let srv_config = config::ServerConfig::load_from_env();
|
||||
let srv_addr = format!("{}:{}", srv_config.host, srv_config.port);
|
||||
let srv_listener = TcpListener::bind(&srv_addr)
|
||||
.await
|
||||
.context(format!("failed to bind to address: {}", addr))?;
|
||||
.context(format!("failed to bind to address: {}", srv_addr))?;
|
||||
|
||||
tracing::info!(%addr, "starting server");
|
||||
axum::serve(listener, router.into_make_service())
|
||||
tracing::info!(%srv_addr, "starting server");
|
||||
axum::serve(srv_listener, app_router.into_make_service())
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.context("server stopped unexpectedly")?;
|
||||
|
||||
pool.close().await;
|
||||
db_pool.close().await;
|
||||
|
||||
tracing::info!("server shut down gracefully");
|
||||
Ok(())
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use axum::{extract::State, routing::post};
|
||||
use chrono::{Duration, Utc};
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
config::TokenConfig,
|
||||
crypto::{generate_secret, hash_secret},
|
||||
domain::Token,
|
||||
domain::{self, Token},
|
||||
error::AppError,
|
||||
repository,
|
||||
routes::{
|
||||
@@ -14,19 +15,17 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
const ACCESS_TOKEN_LIFETIME_SECONDS: i64 = 3600;
|
||||
const REFRESH_TOKEN_LIFETIME_SECONDS: i64 = 30 * 24 * 60 * 60;
|
||||
|
||||
pub fn create_router() -> axum::Router<crate::state::AppState> {
|
||||
axum::Router::new()
|
||||
.route("/", post(issue_token))
|
||||
.route("/revoke", post(revoke_token))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool, token_request))]
|
||||
#[axum::debug_handler(state = crate::state::AppState)]
|
||||
#[tracing::instrument(skip(pool, token_config, token_request))]
|
||||
async fn issue_token(
|
||||
State(pool): State<PgPool>,
|
||||
State(token_config): State<TokenConfig>,
|
||||
Form(token_request): Form<TokenRequest>,
|
||||
) -> Result<Json<TokenResponse>, AppError> {
|
||||
match token_request {
|
||||
@@ -34,8 +33,8 @@ async fn issue_token(
|
||||
client_id,
|
||||
client_secret,
|
||||
} => {
|
||||
let token_pair = TokenPair::from_config(&token_config)?;
|
||||
let secret_hash = hash_secret(&client_secret);
|
||||
let generated = generate_token_pair()?;
|
||||
|
||||
if !repository::user_app_secrets::verify(&pool, client_id, &secret_hash).await? {
|
||||
return Err(AppError::InvalidClientCredentials);
|
||||
@@ -45,34 +44,30 @@ async fn issue_token(
|
||||
.await?
|
||||
.ok_or(AppError::InvalidClientCredentials)?;
|
||||
|
||||
repository::tokens::issue(&pool, token(app.user_id, Some(app.id), &generated)).await?;
|
||||
let token = token(&app, &token_pair);
|
||||
|
||||
Ok(Json(token_response(
|
||||
generated.access_token,
|
||||
generated.refresh_token,
|
||||
)))
|
||||
repository::tokens::issue(&pool, token).await?;
|
||||
|
||||
Ok(Json(token_response(&token_pair, &token_config)))
|
||||
}
|
||||
TokenRequest::RefreshToken { refresh_token } => {
|
||||
let old_refresh_hash = hash_secret(&refresh_token);
|
||||
let generated = generate_token_pair()?;
|
||||
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_hash,
|
||||
&generated.access_token_hash,
|
||||
&generated.refresh_token_hash,
|
||||
generated.access_expires_at,
|
||||
generated.refresh_expires_at,
|
||||
&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?
|
||||
{
|
||||
return Err(AppError::InvalidRefreshToken);
|
||||
}
|
||||
|
||||
Ok(Json(token_response(
|
||||
generated.access_token,
|
||||
generated.refresh_token,
|
||||
)))
|
||||
Ok(Json(token_response(&token_pair, &token_config)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,44 +90,46 @@ struct TokenPair {
|
||||
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>,
|
||||
access_expires_at: DateTime<Utc>,
|
||||
refresh_expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
fn generate_token_pair() -> Result<TokenPair, AppError> {
|
||||
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 + Duration::seconds(ACCESS_TOKEN_LIFETIME_SECONDS),
|
||||
refresh_expires_at: now + Duration::seconds(REFRESH_TOKEN_LIFETIME_SECONDS),
|
||||
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_id: Uuid, app_id: Option<Uuid>, token_pair: &TokenPair) -> Token {
|
||||
fn token(user_app: &domain::UserApp, generated: &TokenPair) -> Token {
|
||||
Token {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
user_app_id: app_id,
|
||||
access_token_hash: token_pair.access_token_hash.clone(),
|
||||
refresh_token_hash: token_pair.refresh_token_hash.clone(),
|
||||
access_expires_at: token_pair.access_expires_at,
|
||||
refresh_expires_at: token_pair.refresh_expires_at,
|
||||
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(access_token: String, refresh_token: String) -> TokenResponse {
|
||||
fn token_response(generated: &TokenPair, token_config: &TokenConfig) -> TokenResponse {
|
||||
TokenResponse {
|
||||
access_token,
|
||||
access_token: generated.access_token.clone(),
|
||||
token_type: TokenType::Bearer,
|
||||
expires_in: ACCESS_TOKEN_LIFETIME_SECONDS,
|
||||
refresh_token: Some(refresh_token),
|
||||
expires_in: token_config.access_token_lifetime.num_seconds(),
|
||||
refresh_token: Some(generated.refresh_token.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
+5
-2
@@ -1,13 +1,16 @@
|
||||
use axum::extract::FromRef;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::config::TokenConfig;
|
||||
|
||||
#[derive(Clone, FromRef)]
|
||||
pub struct AppState {
|
||||
pub pool: PgPool,
|
||||
pub token_config: TokenConfig,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
Self { pool }
|
||||
pub fn new(pool: PgPool, token_config: TokenConfig) -> Self {
|
||||
Self { pool, token_config }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user