ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! Organizations (tenants): create, switch, members and roles, invitations, delete. Every org page takes
//! `Member` (the org comes from the `{org}` path segment and membership is checked), so a handler can only
//! ever see its own org. See `controllers/projects.rs` for the tenant-owned example.
use super::AppError;
use crate::{
    AppState, account,
    models::{project, user},
};
use axum::{
    extract::{Path, State},
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Response},
};
use ryuk::{
    auth::{Auth, OptionalAuth},
    inertia::{self, Inertia},
    proxy::ClientIp,
    session::Session,
    tenancy::{Member, Role},
    throttle::Throttle,
    validation::Form,
};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder, QuerySelect};
use serde::Deserialize;
use serde_json::json;
use std::{collections::BTreeMap, time::Duration};
use utoipa::ToSchema;
use validator::Validate;

/// How long an invitation link works.
const INVITE_TTL: Duration = Duration::from_secs(7 * 24 * 3600);
/// Pending invitations one org may have at once (bounds mail volume on top of the throttles).
const MAX_PENDING_INVITES: usize = 100;
/// Members plus pending invitations one org may hold, and organizations one user may belong to: bounds every
/// list this app renders and every `IN (...)` the library runs (SQLite allows 32 766 bind parameters).
const MAX_MEMBERS: usize = 500;
const MAX_ORGS_PER_USER: usize = 25;

#[derive(Deserialize, Validate, ToSchema)]
pub struct OrgForm {
    #[validate(length(min = 1, max = 100, message = "Name must be 1 to 100 characters"))]
    name: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct InviteForm {
    #[validate(email(message = "Enter a valid email address"))]
    email: String,
    /// `member` or `admin`; an invitation never grants `owner`.
    role: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct RoleForm {
    /// `member`, `admin` or `owner`.
    role: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct DeleteOrgForm {
    /// Must equal the organization name.
    confirm: String,
    /// Required when the account has a password.
    password: Option<String>,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct AcceptForm {
    token: String,
}

fn field(name: &str, msg: &str) -> BTreeMap<String, String> {
    BTreeMap::from([(name.to_string(), msg.to_string())])
}

fn not_found() -> Response {
    StatusCode::NOT_FOUND.into_response()
}

/// A member who is not allowed to do this: say so on the page they came from. A bare 403 would make the Inertia client
/// show its raw error modal (an empty frame). Non-members still get the 404 of `Member`: they have no page to go back to.
pub(crate) async fn denied(session: &Session, back: &str) -> Response {
    inertia::flash(session, "error", "You do not have permission to do that.").await;
    inertia::redirect(back)
}

async fn org_name(s: &AppState, org_id: i64) -> Result<String, AppError> {
    Ok(ryuk::tenancy::orgs::Entity::find_by_id(org_id).one(&s.db).await?.map(|o| o.name).unwrap_or_default())
}

fn org_page(id: i64) -> String {
    format!("/orgs/{id}")
}

fn app_url() -> String {
    std::env::var("APP_URL").unwrap_or_else(|_| "http://localhost:3000".into()).trim_end_matches('/').to_string()
}

/// Whether `actor` may move a member from `target` to `new` (also used for removal, with `new` = member).
/// Owners may do anything (the last-owner guard is in the library); admins only manage plain members and
/// can grant at most admin; members manage nobody.
fn may_change(actor: Role, target: Role, new: Role) -> bool {
    actor == Role::Owner || (actor == Role::Admin && target == Role::Member && new <= Role::Admin)
}

#[utoipa::path(get, path = "/orgs", responses((status = 200, description = "Your organizations")))]
pub async fn index(State(s): State<AppState>, Auth(uid): Auth, inertia: Inertia) -> Result<Response, AppError> {
    let orgs: Vec<_> = s
        .tenancy
        .orgs_of(uid)
        .await?
        .into_iter()
        .map(|(o, r)| json!({ "id": o.id, "name": o.name, "role": r }))
        .collect();
    Ok(inertia.render("Orgs/Index", json!({ "orgs": orgs })))
}

#[utoipa::path(post, path = "/orgs", request_body = OrgForm,
    responses((status = 303, description = "Redirect to the new organization")))]
pub async fn store(State(s): State<AppState>, Auth(uid): Auth, session: Session, Form(f): Form<OrgForm>) -> Result<Response, AppError> {
    if s.tenancy.orgs_of(uid).await?.len() >= MAX_ORGS_PER_USER {
        inertia::flash_errors(&session, field("name", &format!("You can belong to at most {MAX_ORGS_PER_USER} organizations."))).await;
        return Ok(inertia::redirect("/orgs"));
    }
    let org = s.tenancy.create_org(uid, f.name.trim()).await?;
    inertia::flash(&session, "success", "Organization created.").await;
    Ok(inertia::redirect(&org_page(org.id)))
}

#[utoipa::path(get, path = "/orgs/{org}", params(("org" = i64, Path, description = "Organization id")),
    responses((status = 200, description = "Members, invitations and projects"), (status = 404, description = "Not a member")))]
pub async fn show(State(s): State<AppState>, m: Member, inertia: Inertia) -> Result<Response, AppError> {
    let Some(org) = ryuk::tenancy::orgs::Entity::find_by_id(m.org_id).one(&s.db).await? else {
        return Ok(not_found());
    };
    let members = s.tenancy.members(m.org_id).await?;
    let users = user::Entity::find().filter(user::Column::Id.is_in(members.iter().map(|x| x.user_id))).all(&s.db).await?;
    let members: Vec<_> = members
        .iter()
        .filter_map(|x| {
            let u = users.iter().find(|u| u.id == x.user_id)?;
            // Co-members' addresses are for admins and owners; a plain member sees names only.
            let email = (m.role >= Role::Admin).then_some(u.email.as_str());
            Some(json!({ "user_id": x.user_id, "name": u.name, "email": email, "role": x.role }))
        })
        .collect();
    // Pending invitations show to admins and owners only: they list other people's email addresses.
    let invites: Vec<_> = if m.role >= Role::Admin {
        s.tenancy
            .pending_invites(m.org_id)
            .await?
            .into_iter()
            .map(|i| json!({ "id": i.id, "email": i.email, "role": i.role, "expires_at": i.expires_at }))
            .collect()
    } else {
        vec![]
    };
    let projects = project::Entity::find()
        .filter(project::Column::OrgId.eq(m.org_id))
        .order_by_desc(project::Column::Id)
        .limit(500)
        .all(&s.db)
        .await?;
    Ok(inertia.render(
        "Orgs/Show",
        json!({ "org": { "id": org.id, "name": org.name }, "role": m.role, "me": m.user_id, "members": members, "invites": invites, "projects": projects }),
    ))
}

#[utoipa::path(post, path = "/orgs/{org}/invitations", params(("org" = i64, Path, description = "Organization id")), request_body = InviteForm,
    responses((status = 303, description = "Back to the organization")))]
pub async fn invite(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    m: Member,
    session: Session,
    Form(f): Form<InviteForm>,
) -> Result<Response, AppError> {
    let page = org_page(m.org_id);
    if m.require(Role::Admin).is_err() {
        return Ok(denied(&session, &page).await);
    }
    let role = match Role::parse(&f.role) {
        Some(r @ (Role::Member | Role::Admin)) if r <= m.role => r,
        _ => {
            inertia::flash_errors(&session, field("role", "Choose member or admin.")).await;
            return Ok(inertia::redirect(&page));
        }
    };
    let email = f.email.trim().to_lowercase();
    // Per inviter+IP and per invited address, like every mail-sending flow: one account cannot flood an inbox.
    let by_user = s.throttle.attempt(&Throttle::key(&format!("invite:{}", m.user_id), ip)).await;
    let by_email = s.mail_throttle.attempt(&Throttle::key(&format!("invite-to:{email}"), None)).await;
    if by_user.is_err() || by_email.is_err() {
        inertia::flash_errors(&session, field("email", "Too many invitations. Try again later.")).await;
        return Ok(inertia::redirect(&page));
    }
    let pending = s.tenancy.pending_invites(m.org_id).await?.len();
    if pending >= MAX_PENDING_INVITES {
        inertia::flash_errors(&session, field("email", "Too many pending invitations. Revoke some first.")).await;
        return Ok(inertia::redirect(&page));
    }
    if pending + s.tenancy.members(m.org_id).await?.len() >= MAX_MEMBERS {
        inertia::flash_errors(&session, field("email", "This organization is full.")).await;
        return Ok(inertia::redirect(&page));
    }
    let token = s.tenancy.invite(m.org_id, m.user_id, &email, role, INVITE_TTL).await?;
    let link = format!("{}/invitations/{token}", app_url());
    let org = org_name(&s, m.org_id).await?;
    let inviter = user::Entity::find_by_id(m.user_id).one(&s.db).await?.map(|u| u.name).unwrap_or_default();
    let mail = crate::mails::org::invitation(&inviter, &org, role.as_str(), &email, &link, INVITE_TTL)?;
    if !ryuk::security::is_production() {
        // The log mail driver quoted-printable wraps long lines, so print the link intact for development.
        tracing::info!("{}: {link}", mail.subject);
    }
    // Mail failures are logged, not shown: the admin can revoke and re-invite.
    if let Err(e) = s.mailer.send(mail).await {
        tracing::error!("invitation mail for org {}: {e}", m.org_id);
    }
    inertia::flash(&session, "success", "Invitation sent.").await;
    Ok(inertia::redirect(&page))
}

#[utoipa::path(delete, path = "/orgs/{org}/invitations/{id}", params(("org" = i64, Path, description = "Organization id"), ("id" = i64, Path, description = "Invitation id")),
    responses((status = 303, description = "Back to the organization"), (status = 404, description = "Not found")))]
pub async fn revoke_invite(State(s): State<AppState>, m: Member, Path(ids): Path<(i64, i64)>, session: Session) -> Result<Response, AppError> {
    if m.require(Role::Admin).is_err() {
        return Ok(denied(&session, &org_page(m.org_id)).await);
    }
    if !s.tenancy.revoke_invite(m.org_id, ids.1).await? {
        return Ok(not_found());
    }
    inertia::flash(&session, "success", "Invitation revoked.").await;
    Ok(inertia::redirect(&org_page(m.org_id)))
}

#[utoipa::path(put, path = "/orgs/{org}/members/{user}", params(("org" = i64, Path, description = "Organization id"), ("user" = i64, Path, description = "User id")), request_body = RoleForm,
    responses((status = 303, description = "Back to the organization"), (status = 404, description = "Not a member")))]
pub async fn set_role(
    State(s): State<AppState>,
    m: Member,
    Path(ids): Path<(i64, i64)>,
    session: Session,
    Form(f): Form<RoleForm>,
) -> Result<Response, AppError> {
    let page = org_page(m.org_id);
    let target = ids.1;
    let (Some(new), Some(current)) = (Role::parse(&f.role), s.tenancy.role(m.org_id, target).await?) else {
        return Ok(not_found());
    };
    if !may_change(m.role, current, new) {
        return Ok(denied(&session, &page).await);
    }
    // Compare-and-set on the role we just authorized against: if it changed since, nothing is overwritten.
    match s.tenancy.change_role(m.org_id, target, current, new).await {
        Ok(true) => inertia::flash(&session, "success", "Role updated.").await,
        Ok(false) => inertia::flash(&session, "error", "That member changed in the meantime. Reload and try again.").await,
        Err(ryuk::tenancy::TenancyError::LastOwner) => inertia::flash(&session, "error", "An organization needs at least one owner.").await,
        Err(e) => return Err(e.into()),
    }
    Ok(inertia::redirect(&page))
}

#[utoipa::path(delete, path = "/orgs/{org}/members/{user}", params(("org" = i64, Path, description = "Organization id"), ("user" = i64, Path, description = "User id")),
    responses((status = 303, description = "Removed (or left)"), (status = 404, description = "Not a member")))]
pub async fn remove_member(
    State(s): State<AppState>,
    m: Member,
    Path(ids): Path<(i64, i64)>,
    session: Session,
) -> Result<Response, AppError> {
    let target = ids.1;
    let Some(current) = s.tenancy.role(m.org_id, target).await? else {
        return Ok(not_found());
    };
    let leaving = target == m.user_id;
    if !leaving && !may_change(m.role, current, Role::Member) {
        return Ok(denied(&session, &org_page(m.org_id)).await);
    }
    match s.tenancy.remove_member(m.org_id, target).await {
        Ok(()) if leaving => {
            inertia::flash(&session, "success", "You left the organization.").await;
            return Ok(inertia::redirect("/orgs"));
        }
        Ok(()) => inertia::flash(&session, "success", "Member removed.").await,
        Err(ryuk::tenancy::TenancyError::LastOwner) => inertia::flash(&session, "error", "An organization needs at least one owner.").await,
        Err(e) => return Err(e.into()),
    }
    Ok(inertia::redirect(&org_page(m.org_id)))
}

#[utoipa::path(delete, path = "/orgs/{org}", params(("org" = i64, Path, description = "Organization id")), request_body = DeleteOrgForm,
    responses((status = 303, description = "Deleted: your organizations; or back with an error")))]
pub async fn destroy(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    m: Member,
    session: Session,
    Form(f): Form<DeleteOrgForm>,
) -> Result<Response, AppError> {
    let page = org_page(m.org_id);
    if m.require(Role::Owner).is_err() {
        return Ok(denied(&session, &page).await);
    }
    let name = org_name(&s, m.org_id).await?;
    if f.confirm != name {
        inertia::flash_errors(&session, field("confirm", "Type the organization name to confirm.")).await;
        return Ok(inertia::redirect(&page));
    }
    let Some(u) = user::Entity::find_by_id(m.user_id).one(&s.db).await? else {
        return Ok(inertia::redirect("/login"));
    };
    if let Err(msg) = account::confirm_password(&s, ip, &u, f.password.as_deref()).await? {
        inertia::flash_errors(&session, field("password", &msg)).await;
        return Ok(inertia::redirect(&page));
    }
    account::delete_org(&s, m.org_id).await?;
    inertia::flash(&session, "success", "Organization deleted.").await;
    Ok(inertia::redirect("/orgs"))
}

#[utoipa::path(get, path = "/invitations/{token}", params(("token" = String, Path, description = "Invitation token")),
    responses((status = 200, description = "Accept page"), (status = 303, description = "Sign in first")))]
pub async fn show_invitation(inertia: Inertia, OptionalAuth(uid): OptionalAuth, Path(token): Path<String>) -> Response {
    // Not signed in: log in first and come back (the login page accepts only local `next` paths).
    if uid.is_none() {
        return inertia::redirect(&format!("/login?next=/invitations/{token}"));
    }
    // A GET never consumes the token (mail scanners open links): the button below POSTs it.
    inertia.render("Invitations/Accept", json!({ "token": token }))
}

#[utoipa::path(post, path = "/invitations/accept", request_body = AcceptForm,
    responses((status = 303, description = "The organization, or back with an error")))]
pub async fn accept(State(s): State<AppState>, Auth(uid): Auth, session: Session, headers: HeaderMap, Form(f): Form<AcceptForm>) -> Result<Response, AppError> {
    let Some(u) = user::Entity::find_by_id(uid).one(&s.db).await? else {
        return Ok(inertia::redirect("/login"));
    };
    // Only a verified address may claim an invitation: anyone can register an unverified account with any email.
    if u.email_verified_at.is_none() {
        inertia::flash(&session, "error", "Verify your email address before accepting an invitation.").await;
        return Ok(inertia::redirect_back(&headers));
    }
    // Same generic answer for unknown, used, expired and wrong-address tokens.
    match s.tenancy.accept(&f.token, uid, &u.email).await? {
        Some(org_id) => {
            inertia::flash(&session, "success", "You joined the organization.").await;
            Ok(inertia::redirect(&org_page(org_id)))
        }
        None => {
            inertia::flash(&session, "error", "This invitation is invalid, expired, or for a different email address.").await;
            Ok(inertia::redirect("/orgs"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::may_change;
    use ryuk::tenancy::Role::{Admin, Member, Owner};

    #[test]
    fn roles_only_manage_those_below_them() {
        assert!(may_change(Owner, Owner, Member) && may_change(Owner, Member, Owner));
        assert!(may_change(Admin, Member, Admin) && may_change(Admin, Member, Member));
        assert!(!may_change(Admin, Member, Owner), "an admin cannot make owners");
        assert!(!may_change(Admin, Admin, Member), "an admin cannot demote another admin");
        assert!(!may_change(Admin, Owner, Member), "an admin cannot touch an owner");
        assert!(!may_change(Member, Member, Member), "a member manages nobody");
    }
}