fastauth 0.2.0

Authentication for Rust web apps, modelled on Better Auth: sessions, email and password, plugins checked by the compiler.
Documentation
//! The app binary's commands end to end on a SQLite file: `generate`, `status`, `migrate`.

use std::path::Path;

use clap::Parser;
use fastauth::cli::Cli;
use fastauth::prelude::*;

#[derive(Fields, Clone, Debug)]
#[expect(dead_code, reason = "only the column it adds to the schema matters")]
struct Profile {
    #[field(default = "free")]
    plan: String,
}

fn build(pool: SqlitePool) -> Result<Auth<Sqlx<Sqlite>, Profile>, BuildError> {
    FastAuth::builder()
        .secret(Secret::from_base64(&Secret::generate()))
        .base_url("http://localhost:3000")
        .database(Sqlx::new(pool))
        .user_fields::<Profile>()
        .build()
}

async fn fastauth(url: &str, args: &[&str]) -> anyhow::Result<()> {
    let argv = ["fastauth", "--database-url", url]
        .into_iter()
        .chain(args.iter().copied());
    Cli::parse_from(argv).run(build).await
}

fn migrations(dir: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .map(|e| e.unwrap().file_name().into_string().unwrap())
        .collect()
}

#[tokio::test]
async fn generate_and_status_on_a_sqlite_file() {
    let tmp = tempfile::tempdir().unwrap();
    let url = format!("sqlite://{}?mode=rwc", tmp.path().join("app.db").display());
    let out = tmp.path().join("migrations");
    let out_arg = out.to_str().unwrap();

    let pending = fastauth(&url, &["status"]).await.unwrap_err();
    assert_eq!(pending.to_string(), "8 migration steps pending");

    fastauth(&url, &["generate", "--out", out_arg])
        .await
        .unwrap();
    let files = migrations(&out);
    assert_eq!(files.len(), 1);
    let name = &files[0];
    assert!(name.ends_with("_fastauth.sql"), "{name}");
    assert_eq!(name.len(), "20261125120000_fastauth.sql".len());
    assert!(name[..14].bytes().all(|b| b.is_ascii_digit()), "{name}");
    let sql = std::fs::read_to_string(out.join(name)).unwrap();
    assert!(sql.starts_with("-- Generated by `fastauth generate`"));
    assert!(sql.contains("CREATE TABLE \"user\""), "{sql}");
    assert!(
        sql.contains("\"plan\" text NOT NULL DEFAULT 'free'"),
        "{sql}"
    );

    assert!(
        fastauth(&url, &["status"]).await.is_err(),
        "generate applies nothing"
    );

    fastauth(&url, &["migrate"]).await.unwrap();
    fastauth(&url, &["status"]).await.unwrap();
    std::fs::remove_dir_all(&out).unwrap();
    fastauth(&url, &["generate", "--out", out_arg])
        .await
        .unwrap();
    assert!(migrations(&out).is_empty(), "an empty plan writes nothing");
}

#[tokio::test]
async fn missing_database_url_is_reported() {
    let cli = Cli::try_parse_from(["fastauth", "status"]).unwrap();
    if std::env::var_os("DATABASE_URL").is_some() {
        return;
    }
    let err = cli.run(build).await.unwrap_err();
    assert!(
        err.to_string().starts_with("DATABASE_URL is not set"),
        "{err}"
    );
}