Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       140       150       160       170       180       190       200       210       220       230       240       250       260       270       280       290       300       3101use std::{env, net::SocketAddr, time::Duration};23use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString};4use axum::{5    Json, Router,6    extract::{FromRequestParts, Path, State},7    http::{StatusCode, header::AUTHORIZATION, request::Parts},8    response::{IntoResponse, Response},9    routing::{get, post},10};11use chrono::{NaiveDate, Utc};12use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};13use rand_core::OsRng;14use serde::{Deserialize, Serialize};15use sqlx::{FromRow, PgPool, postgres::PgPoolOptions};16use thiserror::Error;17use tower_http::trace::TraceLayer;18use utoipa::{OpenApi, ToSchema};19use utoipa_swagger_ui::SwaggerUi;20use uuid::Uuid;2122const TOKEN_TTL_SECONDS: i64 = 60 * 60 * 24;23const MAX_AMOUNT_CENTS: i64 = 100_000_000_000;2425#[derive(Clone)]26struct AppState {27    pool: PgPool,28    jwt_secret: String,29}3031#[derive(Debug, Error)]32enum ApiError {33    #[error("invalid request")]34    Validation(String),35    #[error("email or password is incorrect")]36    Unauthorized,37    #[error("resource not found")]38    NotFound,39    #[error("email is already registered")]40    Conflict,41    #[error("internal server error")]42    Internal(#[from] sqlx::Error),43}4445impl IntoResponse for ApiError {46    fn into_response(self) -> Response {47        let (status, message) = match self {48            Self::Validation(message) => (StatusCode::BAD_REQUEST, message),49            Self::Unauthorized => (50                StatusCode::UNAUTHORIZED,51                "invalid credentials or token".to_owned(),52            ),53            Self::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_owned()),54            Self::Conflict => (55                StatusCode::CONFLICT,56                "email is already registered".to_owned(),57            ),58            Self::Internal(error) => {59                tracing::error!(error = %error, "database operation failed");60                (61                    StatusCode::INTERNAL_SERVER_ERROR,62                    "internal server error".to_owned(),63                )64            }65        };66        (status, Json(ErrorBody { error: message })).into_response()67    }68}6970#[derive(Serialize, ToSchema)]71struct ErrorBody {72    error: String,73}7475#[derive(Deserialize, ToSchema)]76struct Credentials {77    #[schema(example = "person@example.com")]78    email: String,79    #[schema(min_length = 12, example = "correct-horse-battery")]80    password: String,81}8283#[derive(Serialize, ToSchema)]84struct AuthResponse {85    access_token: String,86    token_type: String,87    expires_in: i64,88}8990#[derive(Serialize, FromRow, ToSchema)]91struct Expense {92    id: Uuid,93    amount_cents: i64,94    currency: String,95    description: String,96    occurred_on: NaiveDate,97    created_at: chrono::DateTime<Utc>,98    updated_at: chrono::DateTime<Utc>,99}100101#[derive(Deserialize, ToSchema)]102struct ExpenseInput {103    #[schema(minimum = 1, example = 1299)]104    amount_cents: i64,105    #[schema(min_length = 3, max_length = 3, example = "USD")]106    currency: String,107    #[schema(min_length = 1, max_length = 500, example = "Lunch")]108    description: String,109    #[schema(example = "2026-10-08")]110    occurred_on: NaiveDate,111}112113#[derive(Serialize, FromRow)]114struct User {115    id: Uuid,116    email: String,117    password_hash: String,118}119120#[derive(Serialize, Deserialize)]121struct Claims {122    sub: String,123    exp: i64,124}125126struct AuthUser(Uuid);127128impl FromRequestParts<AppState> for AuthUser {129    type Rejection = ApiError;130131    #[allow(clippy::unused_async_trait_impl)]132    async fn from_request_parts(133        parts: &mut Parts,134        state: &AppState,135    ) -> Result<Self, Self::Rejection> {136        let value = parts137            .headers138            .get(AUTHORIZATION)139            .and_then(|header| header.to_str().ok())140            .and_then(|header| header.strip_prefix("Bearer "))141            .ok_or(ApiError::Unauthorized)?;142        let claims = decode::<Claims>(143            value,144            &DecodingKey::from_secret(state.jwt_secret.as_bytes()),145            &Validation::new(Algorithm::HS256),146        )147        .map_err(|_| ApiError::Unauthorized)?148        .claims;149        let id = Uuid::parse_str(&claims.sub).map_err(|_| ApiError::Unauthorized)?;150        Ok(Self(id))151    }152}153154fn validate_credentials(credentials: &Credentials) -> Result<(String, String), ApiError> {155    let email = credentials.email.trim().to_ascii_lowercase();156    if email.len() > 254 || !email.contains('@') || email.starts_with('@') || email.ends_with('@') {157        return Err(ApiError::Validation(158            "email must be a valid address".to_owned(),159        ));160    }161    if credentials.password.len() < 12 || credentials.password.len() > 128 {162        return Err(ApiError::Validation(163            "password must contain 12 to 128 bytes".to_owned(),164        ));165    }166    Ok((email, credentials.password.clone()))167}168169fn validate_expense(input: &mut ExpenseInput) -> Result<(), ApiError> {170    input.description = input.description.trim().to_owned();171    input.currency = input.currency.trim().to_ascii_uppercase();172    if !(1..=MAX_AMOUNT_CENTS).contains(&input.amount_cents) {173        return Err(ApiError::Validation(174            "amount_cents must be positive and within range".to_owned(),175        ));176    }177    if input.currency.len() != 3 || !input.currency.bytes().all(|byte| byte.is_ascii_uppercase()) {178        return Err(ApiError::Validation(179            "currency must be a three-letter code".to_owned(),180        ));181    }182    if input.description.is_empty() || input.description.chars().count() > 500 {183        return Err(ApiError::Validation(184            "description must contain 1 to 500 characters".to_owned(),185        ));186    }187    Ok(())188}189190fn issue_token(user_id: Uuid, secret: &str) -> Result<AuthResponse, ApiError> {191    let exp = Utc::now().timestamp() + TOKEN_TTL_SECONDS;192    let claims = Claims {193        sub: user_id.to_string(),194        exp,195    };196    let access_token = encode(197        &Header::new(Algorithm::HS256),198        &claims,199        &EncodingKey::from_secret(secret.as_bytes()),200    )201    .map_err(|error| {202        tracing::error!(error = %error, "JWT encoding failed");203        ApiError::Unauthorized204    })?;205    Ok(AuthResponse {206        access_token,207        token_type: "Bearer".to_owned(),208        expires_in: TOKEN_TTL_SECONDS,209    })210}211212#[utoipa::path(post, path = "/api/auth/register", request_body = Credentials, responses((status = 201, body = AuthResponse), (status = 400, body = ErrorBody), (status = 409, body = ErrorBody)))]213async fn register(214    State(state): State<AppState>,215    Json(credentials): Json<Credentials>,216) -> Result<(StatusCode, Json<AuthResponse>), ApiError> {217    let (email, password) = validate_credentials(&credentials)?;218    let salt = SaltString::generate(&mut OsRng);219    let password_hash = Argon2::default()220        .hash_password(password.as_bytes(), &salt)221        .map_err(|_| ApiError::Validation("password could not be processed".to_owned()))?222        .to_string();223    let user = sqlx::query_as::<_, User>("INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING id, email, password_hash")224        .bind(email)225        .bind(password_hash)226        .fetch_one(&state.pool)227        .await228        .map_err(|error| if is_unique_violation(&error) { ApiError::Conflict } else { ApiError::Internal(error) })?;229    tracing::debug!(user_id = %user.id, "registered user");230    Ok((231        StatusCode::CREATED,232        Json(issue_token(user.id, &state.jwt_secret)?),233    ))234}235236#[utoipa::path(post, path = "/api/auth/login", request_body = Credentials, responses((status = 200, body = AuthResponse), (status = 400, body = ErrorBody), (status = 401, body = ErrorBody)))]237async fn login(238    State(state): State<AppState>,239    Json(credentials): Json<Credentials>,240) -> Result<Json<AuthResponse>, ApiError> {241    let (email, password) = validate_credentials(&credentials)?;242    let user =243        sqlx::query_as::<_, User>("SELECT id, email, password_hash FROM users WHERE email = $1")244            .bind(email)245            .fetch_optional(&state.pool)246            .await?247            .ok_or(ApiError::Unauthorized)?;248    let parsed_hash = PasswordHash::new(&user.password_hash).map_err(|_| ApiError::Unauthorized)?;249    Argon2::default()250        .verify_password(password.as_bytes(), &parsed_hash)251        .map_err(|_| ApiError::Unauthorized)?;252    Ok(Json(issue_token(user.id, &state.jwt_secret)?))253}254255#[utoipa::path(post, path = "/api/expenses", request_body = ExpenseInput, security(("bearer_auth" = [])), responses((status = 201, body = Expense), (status = 400, body = ErrorBody), (status = 401, body = ErrorBody)))]256async fn create_expense(257    State(state): State<AppState>,258    AuthUser(user_id): AuthUser,259    Json(mut input): Json<ExpenseInput>,260) -> Result<(StatusCode, Json<Expense>), ApiError> {261    validate_expense(&mut input)?;262    let expense = sqlx::query_as::<_, Expense>("INSERT INTO expenses (user_id, amount_cents, currency, description, occurred_on) VALUES ($1, $2, $3, $4, $5) RETURNING id, amount_cents, currency, description, occurred_on, created_at, updated_at")263        .bind(user_id)264        .bind(input.amount_cents)265        .bind(input.currency)266        .bind(input.description)267        .bind(input.occurred_on)268        .fetch_one(&state.pool)269        .await?;270    Ok((StatusCode::CREATED, Json(expense)))271}272273#[utoipa::path(get, path = "/api/expenses", security(("bearer_auth" = [])), responses((status = 200, body = [Expense]), (status = 401, body = ErrorBody)))]274async fn list_expenses(275    State(state): State<AppState>,276    AuthUser(user_id): AuthUser,277) -> Result<Json<Vec<Expense>>, ApiError> {278    let expenses = sqlx::query_as::<_, Expense>("SELECT id, amount_cents, currency, description, occurred_on, created_at, updated_at FROM expenses WHERE user_id = $1 ORDER BY occurred_on DESC, created_at DESC")279        .bind(user_id)280        .fetch_all(&state.pool)281        .await?;282    Ok(Json(expenses))283}284285#[utoipa::path(get, path = "/api/expenses/{id}", params(("id" = Uuid, Path, description = "Expense ID")), security(("bearer_auth" = [])), responses((status = 200, body = Expense), (status = 401, body = ErrorBody), (status = 404, body = ErrorBody)))]286async fn get_expense(287    State(state): State<AppState>,288    AuthUser(user_id): AuthUser,289    Path(id): Path<Uuid>,290) -> Result<Json<Expense>, ApiError> {291    let expense = find_expense(&state.pool, user_id, id).await?;292    Ok(Json(expense))293}294295#[utoipa::path(put, path = "/api/expenses/{id}", params(("id" = Uuid, Path, description = "Expense ID")), request_body = ExpenseInput, security(("bearer_auth" = [])), responses((status = 200, body = Expense), (status = 400, body = ErrorBody), (status = 401, body = ErrorBody), (status = 404, body = ErrorBody)))]296async fn update_expense(297    State(state): State<AppState>,298    AuthUser(user_id): AuthUser,299    Path(id): Path<Uuid>,300    Json(mut input): Json<ExpenseInput>,301) -> Result<Json<Expense>, ApiError> {302    validate_expense(&mut input)?;303    let expense = sqlx::query_as::<_, Expense>("UPDATE expenses SET amount_cents = $1, currency = $2, description = $3, occurred_on = $4, updated_at = now() WHERE id = $5 AND user_id = $6 RETURNING id, amount_cents, currency, description, occurred_on, created_at, updated_at")304        .bind(input.amount_cents)305        .bind(input.currency)306        .bind(input.description)307        .bind(input.occurred_on)308        .bind(id)309        .bind(user_id)310        .fetch_optional(&state.pool)311        .await?312        .ok_or(ApiError::NotFound)?;313    Ok(Json(expense))314}315316#[utoipa::path(delete, path = "/api/expenses/{id}", params(("id" = Uuid, Path, description = "Expense ID")), security(("bearer_auth" = [])), responses((status = 204, description = "Expense deleted"), (status = 401, body = ErrorBody), (status = 404, body = ErrorBody)))]317async fn delete_expense(318    State(state): State<AppState>,319    AuthUser(user_id): AuthUser,320    Path(id): Path<Uuid>,321) -> Result<StatusCode, ApiError> {322    let result = sqlx::query("DELETE FROM expenses WHERE id = $1 AND user_id = $2")323        .bind(id)324        .bind(user_id)325        .execute(&state.pool)326        .await?;327    if result.rows_affected() == 0 {328        return Err(ApiError::NotFound);329    }330    Ok(StatusCode::NO_CONTENT)331}332333async fn find_expense(pool: &PgPool, user_id: Uuid, id: Uuid) -> Result<Expense, ApiError> {334    sqlx::query_as::<_, Expense>("SELECT id, amount_cents, currency, description, occurred_on, created_at, updated_at FROM expenses WHERE id = $1 AND user_id = $2")335        .bind(id)336        .bind(user_id)337        .fetch_optional(pool)338        .await?339        .ok_or(ApiError::NotFound)340}341342fn is_unique_violation(error: &sqlx::Error) -> bool {343    error344        .as_database_error()345        .is_some_and(|database_error| database_error.code().as_deref() == Some("23505"))346}347348#[utoipa::path(get, path = "/health", responses((status = 200, description = "API is running")))]349async fn health() -> &'static str {350    "ok"351}352353#[derive(OpenApi)]354#[openapi(355    paths(health, register, login, create_expense, list_expenses, get_expense, update_expense, delete_expense),356    components(schemas(ErrorBody, Credentials, AuthResponse, ExpenseInput, Expense)),357    modifiers(&SecurityAddon),358    tags((name = "auth", description = "Account registration and login"), (name = "expenses", description = "Authenticated expense management"))359)]360struct ApiDoc;361362struct SecurityAddon;363364impl utoipa::Modify for SecurityAddon {365    fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {366        if let Some(components) = openapi.components.as_mut() {367            components.add_security_scheme(368                "bearer_auth",369                utoipa::openapi::security::SecurityScheme::Http(370                    utoipa::openapi::security::Http::new(371                        utoipa::openapi::security::HttpAuthScheme::Bearer,372                    ),373                ),374            );375        }376    }377}378379fn app(state: AppState) -> Router {380    Router::new()381        .route("/health", get(health))382        .route("/api/auth/register", post(register))383        .route("/api/auth/login", post(login))384        .route("/api/expenses", post(create_expense).get(list_expenses))385        .route(386            "/api/expenses/{id}",387            get(get_expense).put(update_expense).delete(delete_expense),388        )389        .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()))390        .layer(TraceLayer::new_for_http())391        .with_state(state)392}393394#[tokio::main]395async fn main() -> Result<(), Box<dyn std::error::Error>> {396    dotenvy::dotenv().ok();397    tracing_subscriber::fmt()398        .with_env_filter(399            tracing_subscriber::EnvFilter::try_from_default_env()400                .unwrap_or_else(|_| "expense_tracker_api=info,tower_http=info".into()),401        )402        .init();403404    let database_url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL must be set")?;405    let jwt_secret = env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set")?;406    if jwt_secret.len() < 32 {407        return Err("JWT_SECRET must be at least 32 bytes".into());408    }409    let bind_address: SocketAddr = env::var("BIND_ADDR")410        .unwrap_or_else(|_| "127.0.0.1:3000".to_owned())411        .parse()?;412    let pool = PgPoolOptions::new()413        .max_connections(10)414        .acquire_timeout(Duration::from_secs(5))415        .connect(&database_url)416        .await?;417    sqlx::migrate!("./migrations").run(&pool).await?;418419    let listener = tokio::net::TcpListener::bind(bind_address).await?;420    tracing::info!(address = %bind_address, "expense tracker API listening");421    axum::serve(listener, app(AppState { pool, jwt_secret }))422        .with_graceful_shutdown(shutdown_signal())423        .await?;424    Ok(())425}426427async fn shutdown_signal() {428    let ctrl_c = async {429        if let Err(error) = tokio::signal::ctrl_c().await {430            tracing::error!(error = %error, "failed to install Ctrl+C handler");431        }432    };433    #[cfg(unix)]434    let terminate = async {435        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {436            Ok(mut signal) => {437                signal.recv().await;438            }439            Err(error) => tracing::error!(error = %error, "failed to install SIGTERM handler"),440        }441    };442    #[cfg(not(unix))]443    let terminate = std::future::pending::<()>();444    tokio::select! { () = ctrl_c => {}, () = terminate => {} }445}446447#[cfg(test)]448mod tests {449    use super::*;450    use axum::{body::Body, http::Request};451    use tower::ServiceExt;452453    #[test]454    fn normalizes_valid_credentials_and_rejects_short_passwords() {455        let valid = Credentials {456            email: "  Person@Example.COM ".to_owned(),457            password: "long-enough-password".to_owned(),458        };459        let (email, _) = validate_credentials(&valid).expect("credentials should be valid");460        assert_eq!(email, "person@example.com");461        let invalid = Credentials {462            email: "person@example.com".to_owned(),463            password: "short".to_owned(),464        };465        assert!(validate_credentials(&invalid).is_err());466    }467468    #[test]469    fn validates_and_normalizes_expense_input() {470        let mut input = ExpenseInput {471            amount_cents: 1299,472            currency: " usd ".to_owned(),473            description: "  Lunch  ".to_owned(),474            occurred_on: NaiveDate::from_ymd_opt(2026, 10, 8).expect("valid date"),475        };476        validate_expense(&mut input).expect("expense should be valid");477        assert_eq!(input.currency, "USD");478        assert_eq!(input.description, "Lunch");479480        input.amount_cents = 0;481        assert!(validate_expense(&mut input).is_err());482    }483484    #[test]485    fn issues_a_verifiable_bearer_token() {486        let user_id = Uuid::new_v4();487        let response = issue_token(user_id, "a-test-secret-with-at-least-32-bytes")488            .expect("token should be created");489        let claims = decode::<Claims>(490            &response.access_token,491            &DecodingKey::from_secret("a-test-secret-with-at-least-32-bytes".as_bytes()),492            &Validation::new(Algorithm::HS256),493        )494        .expect("token should verify")495        .claims;496        assert_eq!(claims.sub, user_id.to_string());497        assert_eq!(response.token_type, "Bearer");498    }499500    #[tokio::test]501    async fn health_openapi_and_auth_guard_work_without_a_database_connection() {502        let pool = PgPoolOptions::new()503            .connect_lazy("postgresql://localhost/expense_tracker")504            .expect("database URL should parse without connecting");505        let router = app(AppState {506            pool,507            jwt_secret: "a-test-secret-with-at-least-32-bytes".to_owned(),508        });509510        let health = router511            .clone()512            .oneshot(513                Request::builder()514                    .uri("/health")515                    .body(Body::empty())516                    .expect("request should build"),517            )518            .await519            .expect("health route should respond");520        assert_eq!(health.status(), StatusCode::OK);521522        let openapi = router523            .clone()524            .oneshot(525                Request::builder()526                    .uri("/api-doc/openapi.json")527                    .body(Body::empty())528                    .expect("request should build"),529            )530            .await531            .expect("OpenAPI route should respond");532        assert_eq!(openapi.status(), StatusCode::OK);533534        let protected = router535            .oneshot(536                Request::builder()537                    .uri("/api/expenses")538                    .body(Body::empty())539                    .expect("request should build"),540            )541            .await542            .expect("protected route should reject missing credentials");543        assert_eq!(protected.status(), StatusCode::UNAUTHORIZED);544    }545}