ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! DB-backed single-use tokens for email verification and password reset
//! (table `one_time_tokens`, self-created, SQLite/PostgreSQL/MySQL).
//!
//! The plaintext token (32 random bytes from the OS RNG, base64url) is returned once by
//! [`Tokens::issue`] and never stored; only its sha256 is. Lookup goes through the unique hash
//! index, so no secret is ever compared in application code.
//!
//! ```ignore
//! let tokens = Tokens::new(db);
//! tokens.ensure_tables().await?;
//! let t = tokens.issue(user.id, tokens::RESET_PASSWORD, Duration::from_secs(3600)).await?;
//! // later, from the emailed link:
//! if let Some(user_id) = tokens.consume(&t, tokens::RESET_PASSWORD).await? { /* set password */ }
//! ```
use sea_orm::entity::prelude::*;
use sea_orm::{
    ActiveValue::Set, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter, Schema,
    TransactionTrait,
};
use sha2::{Digest, Sha256};
use std::time::Duration;

/// Purpose for email verification links.
pub const VERIFY_EMAIL: &str = "verify_email";
/// Purpose for password reset links.
pub const RESET_PASSWORD: &str = "reset_password";

/// `one_time_tokens` table.
pub mod one_time_tokens {
    use sea_orm::entity::prelude::*;
    /// A hashed, expiring token.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "one_time_tokens")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        pub user_id: i64,
        pub purpose: String,
        /// Lowercase hex sha256 of the plaintext token.
        #[sea_orm(unique)]
        pub token_hash: String,
        /// Unix seconds; the token is invalid at and after this instant.
        pub expires_at: i64,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}
use one_time_tokens::{Column, Entity};

/// Token storage or randomness failure.
#[derive(Debug, thiserror::Error)]
pub enum TokenError {
    /// Database error.
    #[error("database: {0}")]
    Db(#[from] DbErr),
    /// The OS random number generator failed.
    #[error("OS random number generator failed")]
    Rng,
}

/// Issues and consumes one-time tokens.
#[derive(Clone)]
pub struct Tokens {
    db: DatabaseConnection,
}

fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

fn hash(token: &str) -> String {
    Sha256::digest(token.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// base64url without padding (32 bytes -> 43 chars).
fn b64url(bytes: &[u8]) -> String {
    const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity(bytes.len() * 4 / 3 + 3);
    for c in bytes.chunks(3) {
        let n = (c[0] as u32) << 16
            | (*c.get(1).unwrap_or(&0) as u32) << 8
            | *c.get(2).unwrap_or(&0) as u32;
        for i in 0..=c.len() {
            out.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
        }
    }
    out
}

/// Delete exactly the live token with this hash and purpose; the row count decides who won.
fn consume_q(hash: &str, purpose: &str, now: i64) -> sea_orm::DeleteMany<Entity> {
    Entity::delete_many()
        .filter(Column::TokenHash.eq(hash))
        .filter(Column::Purpose.eq(purpose))
        .filter(Column::ExpiresAt.gt(now))
}

impl Tokens {
    /// New token store over `db`.
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }

    /// Create `one_time_tokens` if missing.
    pub async fn ensure_tables(&self) -> Result<(), DbErr> {
        let mut t = Schema::new(self.db.get_database_backend()).create_table_from_entity(Entity);
        self.db.execute(t.if_not_exists()).await?;
        Ok(())
    }

    /// Mint a token for `user_id` and `purpose`, replacing any earlier one for that pair.
    /// Returns the plaintext (embed it in the emailed link); it cannot be recovered later.
    ///
    /// shortcut: replace is delete-then-insert in a transaction, not a unique (user, purpose)
    /// index, so two simultaneous issues for one pair may both survive (both single-use, both
    /// expiring). Add the composite unique index if that matters.
    pub async fn issue(
        &self,
        user_id: i64,
        purpose: &str,
        ttl: Duration,
    ) -> Result<String, TokenError> {
        use rand::TryRng;
        let mut raw = [0u8; 32];
        rand::rngs::SysRng
            .try_fill_bytes(&mut raw)
            .map_err(|_| TokenError::Rng)?;
        let token = b64url(&raw);
        let tx = self.db.begin().await?;
        Entity::delete_many()
            .filter(Column::UserId.eq(user_id))
            .filter(Column::Purpose.eq(purpose))
            .exec(&tx)
            .await?;
        one_time_tokens::ActiveModel {
            user_id: Set(user_id),
            purpose: Set(purpose.into()),
            token_hash: Set(hash(&token)),
            expires_at: Set(now().saturating_add(ttl.as_secs().min(i64::MAX as u64 / 2) as i64)),
            ..Default::default()
        }
        .insert(&tx)
        .await?;
        tx.commit().await?;
        Ok(token)
    }

    /// Redeem a token: `Some(user_id)` exactly once, `None` if unknown, expired, used or for
    /// another purpose (a wrong-purpose attempt does not burn the token).
    pub async fn consume(&self, token: &str, purpose: &str) -> Result<Option<i64>, TokenError> {
        let h = hash(token);
        let t = now();
        let Some(row) = Entity::find()
            .filter(Column::TokenHash.eq(h.as_str()))
            .filter(Column::Purpose.eq(purpose))
            .filter(Column::ExpiresAt.gt(t))
            .one(&self.db)
            .await?
        else {
            return Ok(None);
        };
        // The delete is the atomic claim: of N racing consumers exactly one sees rows_affected == 1.
        // (DELETE ... RETURNING would save the read but MySQL has no RETURNING.)
        let won = consume_q(&h, purpose, t)
            .exec(&self.db)
            .await?
            .rows_affected
            == 1;
        Ok(won.then_some(row.user_id))
    }

    /// Delete expired tokens; returns how many.
    pub async fn prune(&self) -> Result<u64, TokenError> {
        Ok(Entity::delete_many()
            .filter(Column::ExpiresAt.lte(now()))
            .exec(&self.db)
            .await?
            .rows_affected)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sea_orm::{DbBackend, QueryTrait};

    #[cfg(feature = "sqlite")]
    /// A SQLite file DB (several pooled connections, so concurrency is real) plus external servers when configured.
    async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
        let ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!("ryuk-tokens-{ns}.db"));
        let mut v = vec![(
            "sqlite",
            sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
                .await
                .unwrap(),
        )];
        for (name, var) in [
            ("postgres", "TEST_POSTGRES_URL"),
            ("mysql", "TEST_MYSQL_URL"),
        ] {
            if let Ok(url) = std::env::var(var) {
                v.push((name, sea_orm::Database::connect(url).await.unwrap()));
            }
        }
        v
    }

    #[cfg(feature = "sqlite")]
    const HOUR: Duration = Duration::from_secs(3600);

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn single_use_purpose_expiry_replace_prune() {
        for (name, db) in dbs().await {
            let t = Tokens::new(db.clone());
            t.ensure_tables().await.unwrap();
            t.ensure_tables().await.unwrap();
            let uid = 7;

            let tok = t.issue(uid, RESET_PASSWORD, HOUR).await.unwrap();
            assert_eq!(tok.len(), 43, "{name}");
            assert_eq!(
                t.consume(&tok, VERIFY_EMAIL).await.unwrap(),
                None,
                "{name}: wrong purpose"
            );
            assert_eq!(
                t.consume(&tok, RESET_PASSWORD).await.unwrap(),
                Some(uid),
                "{name}: wrong purpose must not burn it"
            );
            assert_eq!(
                t.consume(&tok, RESET_PASSWORD).await.unwrap(),
                None,
                "{name}: single use"
            );
            assert_eq!(t.consume("garbage", RESET_PASSWORD).await.unwrap(), None);

            // hash at rest: plaintext appears nowhere in the table
            let tok = t.issue(uid, RESET_PASSWORD, HOUR).await.unwrap();
            let rows = Entity::find().all(&db).await.unwrap();
            assert_eq!(rows.len(), 1);
            assert_ne!(rows[0].token_hash, tok);
            assert_eq!(rows[0].token_hash, hash(&tok));
            assert!(!format!("{rows:?}").contains(&tok));

            // re-issue replaces the old token, other purposes/users untouched
            let other = t.issue(uid, VERIFY_EMAIL, HOUR).await.unwrap();
            let newer = t.issue(uid, RESET_PASSWORD, HOUR).await.unwrap();
            assert_eq!(
                t.consume(&tok, RESET_PASSWORD).await.unwrap(),
                None,
                "{name}: replaced"
            );
            assert_eq!(t.consume(&newer, RESET_PASSWORD).await.unwrap(), Some(uid));
            assert_eq!(t.consume(&other, VERIFY_EMAIL).await.unwrap(), Some(uid));

            // expiry enforced server-side
            let old = t.issue(uid, VERIFY_EMAIL, HOUR).await.unwrap();
            Entity::update_many()
                .col_expr(
                    Column::ExpiresAt,
                    sea_orm::sea_query::Expr::value(now() - 1),
                )
                .exec(&db)
                .await
                .unwrap();
            assert_eq!(
                t.consume(&old, VERIFY_EMAIL).await.unwrap(),
                None,
                "{name}: expired"
            );
            assert_eq!(t.prune().await.unwrap(), 1);
            assert!(Entity::find().all(&db).await.unwrap().is_empty());
            assert_eq!(
                t.issue(uid, VERIFY_EMAIL, Duration::ZERO)
                    .await
                    .map(|x| x.len())
                    .unwrap(),
                43
            );
        }
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn concurrent_consume_has_one_winner() {
        for (name, db) in dbs().await {
            let t = Tokens::new(db);
            t.ensure_tables().await.unwrap();
            for round in 0..5 {
                let tok = t.issue(round, RESET_PASSWORD, HOUR).await.unwrap();
                let hs: Vec<_> = (0..16)
                    .map(|_| {
                        let (t, tok) = (t.clone(), tok.clone());
                        tokio::spawn(async move { t.consume(&tok, RESET_PASSWORD).await.unwrap() })
                    })
                    .collect();
                let mut wins = 0;
                for h in hs {
                    wins += h.await.unwrap().is_some() as u32;
                }
                assert_eq!(wins, 1, "{name} round {round}");
            }
        }
    }

    #[test]
    fn tokens_are_urlsafe_and_unique() {
        assert_eq!(b64url(&[0xfb, 0xff, 0xfe]), "-__-");
        assert_eq!(b64url(b"Ma"), "TWE");
        assert_eq!(
            hash("abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn sql_text_all_backends() {
        for b in [DbBackend::Sqlite, DbBackend::Postgres, DbBackend::MySql] {
            let s = consume_q("h", "p", 5).build(b).to_string();
            assert!(
                s.starts_with("DELETE FROM")
                    && s.contains("token_hash")
                    && s.contains("purpose")
                    && s.contains("> 5"),
                "{b:?}: {s}"
            );
            assert!(!s.contains("RETURNING"), "{b:?}: {s}");
            let c = b
                .build(&Schema::new(b).create_table_from_entity(Entity))
                .to_string();
            assert!(c.contains("UNIQUE"), "{b:?}: {c}");
        }
    }
}