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