ryuk-cli 0.1.0

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! Social login glue: provider config and the local-user side of the ryuk::social flow.
use crate::models::{oauth_identity as identity, user};
use ryuk::{
    auth::hash_password_async,
    health::BoxFuture,
    social::{GitHub, Google, Social, SocialError, SocialProfile, SocialUsers},
};
use sea_orm::{
    ActiveModelTrait, ActiveValue::Set, ColumnTrait, DatabaseConnection, DbErr, EntityTrait, QueryFilter,
    prelude::Uuid,
};

/// GitHub and Google, each enabled only when its `*_CLIENT_ID` / `*_CLIENT_SECRET` env vars are set.
pub fn social() -> Social {
    Social::new().github(GitHub::from_env()).google(Google::from_env()).after_login("/dashboard")
}

/// Names of the configured providers (the login/register pages show a button for each).
pub fn enabled(social: &Social) -> Vec<&'static str> {
    social.providers()
}

const UNVERIFIED: &str = "The provider has not verified this email address. Verify it there, or create an account with email and password first.";
const EXISTS: &str = "An account with this email exists. Log in first and link the provider.";

/// Maps provider profiles to local users.
///
/// Linking policy (an unverified email must never hand someone else's account to a provider login):
/// 1. an identity (provider, subject) exists: that user.
/// 2. the provider verified the email AND a local user has it AND that user verified it too: link.
/// 3. a local user has the email otherwise (unverified locally or at the provider): refuse.
/// 4. no such user and the provider verified the email: create one (random unusable password) and the identity.
///    An unverified provider email NEVER creates an account (anyone could claim any address at some providers).
pub struct AppUsers {
    db: DatabaseConnection,
}

impl AppUsers {
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }

    async fn identity_user(&self, p: &SocialProfile) -> Result<Option<i64>, DbErr> {
        Ok(identity::Entity::find()
            .filter(identity::Column::Provider.eq(p.provider))
            .filter(identity::Column::Subject.eq(p.subject.as_str()))
            .one(&self.db)
            .await?
            .map(|i| i.user_id))
    }

    /// Insert the identity; if a concurrent callback won the unique (provider, subject), use its user.
    async fn link(&self, p: &SocialProfile, user_id: i64) -> Result<i64, DbErr> {
        let row = identity::ActiveModel {
            provider: Set(p.provider.into()),
            subject: Set(p.subject.clone()),
            user_id: Set(user_id),
            email: Set(p.email.clone()),
            created_at: Set(chrono::Utc::now()),
            ..Default::default()
        };
        match row.insert(&self.db).await {
            Ok(_) => Ok(user_id),
            Err(e) => self.identity_user(p).await?.ok_or(e),
        }
    }

    async fn attempt(&self, p: &SocialProfile) -> Result<i64, Fail> {
        if let Some(uid) = self.identity_user(p).await? {
            return Ok(uid);
        }
        let email = p.email.as_deref().ok_or_else(|| Fail::Refused("The provider did not share an email address.".into()))?;
        if let Some(u) = user::Entity::find().filter(user::Column::Email.eq(email)).one(&self.db).await? {
            if p.email_verified && u.email_verified_at.is_some() {
                return Ok(self.link(p, u.id).await?);
            }
            return Err(Fail::Refused(EXISTS.into()));
        }
        if !p.email_verified {
            return Err(Fail::Refused(UNVERIFIED.into()));
        }
        // 32 bytes of OS randomness (two v4 UUIDs): nobody knows this password until a reset.
        let secret = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
        let name = p.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or_else(|| email.split('@').next().unwrap_or(email).into());
        let created = user::ActiveModel {
            name: Set(name),
            email: Set(email.into()),
            password: Set(hash_password_async(secret).await.map_err(|e| Fail::Db(DbErr::Custom(e.to_string())))?),
            email_verified_at: Set(Some(chrono::Utc::now())),
            has_usable_password: Set(false),
            ..Default::default()
        }
        .insert(&self.db)
        .await;
        match created {
            Ok(u) => Ok(self.link(p, u.id).await?),
            Err(e) => Err(Fail::Race(e)),
        }
    }
}

enum Fail {
    Refused(String),
    /// User insert failed, most likely a concurrent sign-up took the email: decide again.
    Race(DbErr),
    Db(DbErr),
}

impl From<DbErr> for Fail {
    fn from(e: DbErr) -> Self {
        Fail::Db(e)
    }
}

impl SocialUsers for AppUsers {
    fn resolve<'a>(&'a self, p: &'a SocialProfile) -> BoxFuture<'a, Result<i64, SocialError>> {
        Box::pin(async move {
            let mut res = self.attempt(p).await;
            if matches!(res, Err(Fail::Race(_))) {
                res = self.attempt(p).await; // now sees the winner's identity or user
            }
            res.map_err(|f| match f {
                Fail::Refused(m) => SocialError(m),
                Fail::Race(e) | Fail::Db(e) => {
                    tracing::error!(error = %e, "social login failed");
                    SocialError("Could not sign you in.".into())
                }
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::migrations::Migrator;
    use ryuk::auth::{hash_password, verify_password};
    use sea_orm_migration::MigratorTrait;

    /// `TEST_DATABASE_URL` (postgres/mysql) or in-memory SQLite; rows are unique per run, never cleaned.
    async fn setup() -> (AppUsers, String) {
        let url = std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite::memory:".into());
        let db = ryuk::db::connect(&url).await.unwrap();
        Migrator::up(&db, None).await.unwrap();
        (AppUsers::new(db), Uuid::new_v4().simple().to_string())
    }

    fn prof(tag: &str, subject: &str, verified: bool) -> SocialProfile {
        SocialProfile {
            provider: "github",
            subject: format!("{tag}-{subject}"),
            email: Some(format!("{tag}@example.com")),
            email_verified: verified,
            name: Some("Ada".into()),
        }
    }

    async fn local(u: &AppUsers, tag: &str, verified: bool) -> user::Model {
        user::ActiveModel {
            name: Set("Local".into()),
            email: Set(format!("{tag}@example.com")),
            password: Set(hash_password("hunter2hunter2").unwrap()),
            email_verified_at: Set(verified.then(chrono::Utc::now)),
            has_usable_password: Set(true),
            ..Default::default()
        }
        .insert(&u.db)
        .await
        .unwrap()
    }

    async fn identities(u: &AppUsers, p: &SocialProfile) -> usize {
        identity::Entity::find().filter(identity::Column::Subject.eq(p.subject.as_str())).all(&u.db).await.unwrap().len()
    }

    #[test]
    fn enabled_lists_only_configured_providers() {
        assert!(enabled(&Social::new()).is_empty());
        assert_eq!(enabled(&Social::new().google(Google::new("id", "secret"))), ["google"]);
    }

    #[tokio::test]
    async fn case1_existing_identity_returns_its_user() {
        let (u, t) = setup().await;
        let p = prof(&t, "a", true);
        let id = u.resolve(&p).await.unwrap();
        // Even if the provider email later changes or is unverified, the identity wins.
        let again = SocialProfile { email: Some("new@example.com".into()), email_verified: false, ..p.clone() };
        assert_eq!(u.resolve(&again).await.unwrap(), id);
        assert_eq!(identities(&u, &p).await, 1);
    }

    #[tokio::test]
    async fn case2_verified_both_sides_links() {
        let (u, t) = setup().await;
        let l = local(&u, &t, true).await;
        let p = prof(&t, "b", true);
        assert_eq!(u.resolve(&p).await.unwrap(), l.id);
        assert_eq!(identities(&u, &p).await, 1);
    }

    #[tokio::test]
    async fn case3_unverified_local_account_is_not_linked() {
        let (u, t) = setup().await;
        let l = local(&u, &t, false).await;
        let p = prof(&t, "c", true);
        assert_eq!(u.resolve(&p).await.unwrap_err().0, EXISTS);
        assert_eq!(identities(&u, &p).await, 0);
        assert!(user::Entity::find_by_id(l.id).one(&u.db).await.unwrap().unwrap().email_verified_at.is_none());
    }

    #[tokio::test]
    async fn case3_provider_unverified_email_is_not_linked() {
        let (u, t) = setup().await;
        local(&u, &t, true).await;
        let p = prof(&t, "d", false);
        assert_eq!(u.resolve(&p).await.unwrap_err().0, EXISTS);
        assert_eq!(identities(&u, &p).await, 0);
    }

    #[tokio::test]
    async fn case4_creates_user_with_unusable_password() {
        let (u, t) = setup().await;
        let p = prof(&format!("{t}e1"), "e1", true);
        let id = u.resolve(&p).await.unwrap();
        let row = user::Entity::find_by_id(id).one(&u.db).await.unwrap().unwrap();
        assert!(row.email_verified_at.is_some() && !row.has_usable_password);
        assert!(row.password.starts_with("$argon2"));
        assert!(!verify_password("", &row.password) && !verify_password("password", &row.password));
        assert_eq!(identities(&u, &p).await, 1);
    }

    #[tokio::test]
    async fn case4_unverified_provider_email_never_creates_an_account() {
        let (u, t) = setup().await;
        let p = prof(&format!("{t}e2"), "e2", false);
        assert_eq!(u.resolve(&p).await.unwrap_err().0, UNVERIFIED);
        assert_eq!(identities(&u, &p).await, 0);
        assert!(user::Entity::find().filter(user::Column::Email.eq(p.email.as_deref().unwrap())).one(&u.db).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn concurrent_double_signup_yields_one_user_one_identity() {
        let (u, t) = setup().await;
        let p = prof(&t, "f", true);
        let rs = futures_join(&u, &p).await;
        assert_eq!(rs.0, rs.1);
        assert_eq!(identities(&u, &p).await, 1);
        let users = user::Entity::find().filter(user::Column::Email.eq(p.email.as_deref().unwrap())).all(&u.db).await.unwrap();
        assert_eq!(users.len(), 1);
    }

    async fn futures_join(u: &AppUsers, p: &SocialProfile) -> (i64, i64) {
        let (a, b) = tokio::join!(u.resolve(p), u.resolve(p));
        (a.unwrap(), b.unwrap())
    }
}