rustango 0.27.7

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! User-account verbs: `create-operator` (registry-side, slice 6) and
//! `create-user` (per-tenant, slice 6).

use std::io::Write;

use crate::core::Column as _;
use crate::sql::{Auto, Fetcher};

use crate::tenancy::error::TenancyError;
use crate::tenancy::manage::args::{next_value, quote_ident};
use crate::tenancy::manage_interactive;
use crate::tenancy::pools::TenantPools;

// ---------- create-operator (Slice 6) ----------

pub(super) async fn create_operator_cmd<W: Write + Send>(
    pools: &TenantPools,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    let mut iter = args.iter();
    let username_arg = iter.next().cloned();
    let mut password: Option<String> = None;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--password" => password = Some(next_value(&mut iter, "--password")?),
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "create-operator <username> --password <p>".into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "create-operator: unknown argument `{other}`"
                )));
            }
        }
    }
    // Prompt for missing values when stdin is a TTY; programmatic
    // callers that pass `None` on a non-interactive stream still get
    // the original Validation error.
    let username = match username_arg {
        Some(u) => u,
        None => manage_interactive::ask("Username: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation(
                    "create-operator requires a username positional argument".into(),
                )
            })?,
    };
    let plain = match password {
        Some(p) => p,
        None => manage_interactive::ask_password("Password: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation("create-operator requires --password".into())
            })?,
    };

    // Reject duplicate username up front.
    let existing: Vec<crate::tenancy::Operator> = crate::tenancy::Operator::objects()
        .where_(crate::tenancy::Operator::username.eq(username.clone()))
        .fetch(pools.registry())
        .await?;
    if !existing.is_empty() {
        return Err(TenancyError::Validation(format!(
            "operator `{username}` already exists in the registry"
        )));
    }

    let mut op = crate::tenancy::Operator {
        id: Auto::default(),
        username: username.clone(),
        password_hash: crate::tenancy::password::hash(&plain)?,
        active: true,
        created_at: chrono::Utc::now(),
    };
    op.insert(pools.registry()).await?;
    let id = op.id.get().copied().unwrap_or_default();
    writeln!(w, "created operator `{username}` (id {id})")?;
    Ok(())
}

// ---------- create-user (Slice 6) ----------

pub(super) async fn create_user_cmd<W: Write + Send>(
    pools: &TenantPools,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    let mut iter = args.iter();
    let slug_arg = iter.next().cloned();
    let username_arg = iter.next().cloned();
    let mut password: Option<String> = None;
    let mut is_superuser = false;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--password" => password = Some(next_value(&mut iter, "--password")?),
            "--superuser" => is_superuser = true,
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "create-user <slug> <username> --password <p> [--superuser]".into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "create-user: unknown argument `{other}`"
                )));
            }
        }
    }
    let slug = match slug_arg {
        Some(s) => s,
        None => manage_interactive::ask("Tenant slug: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation(
                    "create-user requires a tenant slug as the first positional argument".into(),
                )
            })?,
    };
    let username = match username_arg {
        Some(u) => u,
        None => manage_interactive::ask("Username: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation(
                    "create-user requires a username as the second positional argument".into(),
                )
            })?,
    };
    let plain = match password {
        Some(p) => p,
        None => manage_interactive::ask_password("Password: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| TenancyError::Validation("create-user requires --password".into()))?,
    };

    // Look up the tenant.
    let orgs: Vec<crate::tenancy::Org> = crate::tenancy::Org::objects()
        .where_(crate::tenancy::Org::slug.eq(slug.clone()))
        .fetch(pools.registry())
        .await?;
    let org = orgs.into_iter().next().ok_or_else(|| {
        TenancyError::Validation(format!("create-user: no tenant with slug `{slug}`"))
    })?;

    let hash = crate::tenancy::password::hash(&plain)?;
    let now = chrono::Utc::now().to_rfc3339();

    // We bypass `User::insert` because that uses `pools.registry()`'s
    // pool by default and we need a connection scoped to the tenant.
    // Hand-write an INSERT against the scoped connection.
    use crate::sql::sqlx::Row;
    use crate::tenancy::org::StorageMode;
    let mode = StorageMode::parse(&org.storage_mode).map_err(|got| {
        TenancyError::Validation(format!("org `{slug}` has unknown storage_mode `{got}`"))
    })?;
    // v0.27.6 — first-user-auto-superuser. When a tenant has zero
    // existing rows in `rustango_users`, the first user we create
    // is implicitly promoted to superuser even if `--superuser`
    // wasn't passed. Pre-fix, an onboarding script that ran
    // `create-user osu admin --password ...` (forgetting
    // `--superuser`) produced a tenant with exactly one user who
    // could log in but saw an empty admin sidebar (no granted
    // CRUD codenames → `is_visible()` returns false for every
    // table). Mirrors Django's `createsuperuser` first-user UX.
    // Caller can still pass `--superuser` for explicit intent;
    // future flag `--no-auto-superuser` could opt out.
    let mut auto_promoted = false;
    if !is_superuser {
        let existing_count: Option<i64> = match mode {
            StorageMode::Schema => {
                let schema = org.schema_name.clone().unwrap_or_else(|| slug.clone());
                let pool = build_schema_scoped_pool(registry_url, &schema).await?;
                let row = rustango::sql::sqlx::query("SELECT COUNT(*) AS n FROM rustango_users")
                    .fetch_one(&pool)
                    .await
                    .ok();
                pool.close().await;
                row.and_then(|r| r.try_get::<i64, _>("n").ok())
            }
            StorageMode::Database => {
                let tp = pools.pool_for_org(&org).await?;
                rustango::sql::sqlx::query("SELECT COUNT(*) AS n FROM rustango_users")
                    .fetch_one(tp.pool())
                    .await
                    .ok()
                    .and_then(|r| r.try_get::<i64, _>("n").ok())
            }
        };
        if existing_count == Some(0) {
            is_superuser = true;
            auto_promoted = true;
        }
    }
    let row_id: i64 = match mode {
        StorageMode::Schema => {
            // Fresh search-path-bound pool so the INSERT lands in the
            // tenant's schema. Mirrors the migration / admin path.
            let schema = org.schema_name.clone().unwrap_or_else(|| slug.clone());
            let pool = build_schema_scoped_pool(registry_url, &schema).await?;
            let row = rustango::sql::sqlx::query(
                "INSERT INTO rustango_users (username, password_hash, is_superuser, active, created_at) \
                 VALUES ($1, $2, $3, true, $4::timestamptz) RETURNING id",
            )
            .bind(&username)
            .bind(&hash)
            .bind(is_superuser)
            .bind(&now)
            .fetch_one(&pool)
            .await?;
            let id: i64 = row.try_get("id")?;
            pool.close().await;
            id
        }
        StorageMode::Database => {
            let tp = pools.pool_for_org(&org).await?;
            let row = rustango::sql::sqlx::query(
                "INSERT INTO rustango_users (username, password_hash, is_superuser, active, created_at) \
                 VALUES ($1, $2, $3, true, $4::timestamptz) RETURNING id",
            )
            .bind(&username)
            .bind(&hash)
            .bind(is_superuser)
            .bind(&now)
            .fetch_one(tp.pool())
            .await?;
            row.try_get("id")?
        }
    };
    if auto_promoted {
        writeln!(
            w,
            "created user `{username}` in tenant `{slug}` (id {row_id}, superuser=true) — \
             auto-promoted because they're the first user of the tenant; pass `--superuser` \
             explicitly to silence this notice on subsequent setups"
        )?;
    } else {
        writeln!(
            w,
            "created user `{username}` in tenant `{slug}` (id {row_id}, superuser={is_superuser})"
        )?;
    }
    Ok(())
}

// ---------- create-superuser (v0.27.6, #77 partial) ----------

/// Django-shape `create-superuser <slug> <username> [--password <s>]`.
/// Convenience entrypoint that always sets `is_superuser = true` —
/// equivalent to `create-user <slug> <username> --superuser` but
/// with a clearer name and prompts when args are missing.
pub(super) async fn create_superuser_cmd<W: Write + Send>(
    pools: &TenantPools,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    // Forward to `create_user_cmd` with `--superuser` injected.
    let mut forwarded: Vec<String> = args.to_vec();
    if !forwarded.iter().any(|s| s == "--superuser") {
        forwarded.push("--superuser".into());
    }
    create_user_cmd(pools, registry_url, &forwarded, w).await
}

// ---------- set-superuser (v0.27.6) ----------

/// `set-superuser <slug> <username> [--on|--off]` toggles
/// `rustango_users.is_superuser` on an existing tenant user. The
/// non-superuser-can't-see-anything failure mode is the most common
/// reason for this verb existing — a freshly-onboarded user lacks
/// any granted CRUD codenames and the admin sidebar appears empty.
/// Promoting them to superuser bypasses the per-codename check.
pub(super) async fn set_superuser_cmd<W: Write + Send>(
    pools: &TenantPools,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    let mut iter = args.iter();
    let slug = iter.next().cloned().ok_or_else(|| {
        TenancyError::Validation("set-superuser <slug> <username> [--on|--off]".into())
    })?;
    let username = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation("set-superuser requires a username".into()))?;
    let mut on = true;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--on" => on = true,
            "--off" => on = false,
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "set-superuser <slug> <username> [--on|--off]".into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "set-superuser: unknown argument `{other}`"
                )));
            }
        }
    }
    let pool = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let result = rustango::sql::sqlx::query(
        "UPDATE rustango_users SET is_superuser = $1 WHERE username = $2",
    )
    .bind(on)
    .bind(&username)
    .execute(&pool)
    .await?;
    pool.close().await;
    if result.rows_affected() == 0 {
        return Err(TenancyError::Validation(format!(
            "set-superuser: no user `{username}` in tenant `{slug}`"
        )));
    }
    writeln!(
        w,
        "set is_superuser={on} on user `{username}` in tenant `{slug}`"
    )?;
    Ok(())
}

// ---------- reset-password (v0.27.6, #77 partial) ----------

/// `reset-password <slug> <username> [--password <s>]` updates a
/// tenant user's password hash without requiring the current
/// password. Use this from the admin's perspective to recover a
/// locked-out user; tenant users themselves should change their
/// password via the (still-pending #77) self-serve UI.
pub(super) async fn reset_password_cmd<W: Write + Send>(
    pools: &TenantPools,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    let mut iter = args.iter();
    let slug = iter.next().cloned().ok_or_else(|| {
        TenancyError::Validation("reset-password <slug> <username> [--password <s>]".into())
    })?;
    let username = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation("reset-password requires a username".into()))?;
    let mut password: Option<String> = None;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--password" => password = Some(next_value(&mut iter, "--password")?),
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "reset-password <slug> <username> [--password <s>]".into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "reset-password: unknown argument `{other}`"
                )));
            }
        }
    }
    let plain = match password {
        Some(p) => p,
        None => manage_interactive::ask_password("New password: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation("reset-password requires --password (or a TTY)".into())
            })?,
    };
    let hash = crate::tenancy::password::hash(&plain)?;
    let pool = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let result = rustango::sql::sqlx::query(
        "UPDATE rustango_users SET password_hash = $1 WHERE username = $2",
    )
    .bind(&hash)
    .bind(&username)
    .execute(&pool)
    .await?;
    pool.close().await;
    if result.rows_affected() == 0 {
        return Err(TenancyError::Validation(format!(
            "reset-password: no user `{username}` in tenant `{slug}`"
        )));
    }
    writeln!(w, "password reset for user `{username}` in tenant `{slug}`")?;
    Ok(())
}

// ---------- reset-operator-password (v0.27.6) ----------

/// `reset-operator-password <username> [--password <s>]` updates an
/// operator's password hash on the registry pool. Recovery path
/// when an operator forgets their password and there's no other
/// admin who can reset via the (pending #77) UI.
pub(super) async fn reset_operator_password_cmd<W: Write + Send>(
    pools: &TenantPools,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    let mut iter = args.iter();
    let username = iter.next().cloned().ok_or_else(|| {
        TenancyError::Validation("reset-operator-password <username> [--password <s>]".into())
    })?;
    let mut password: Option<String> = None;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--password" => password = Some(next_value(&mut iter, "--password")?),
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "reset-operator-password <username> [--password <s>]".into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "reset-operator-password: unknown argument `{other}`"
                )));
            }
        }
    }
    let plain = match password {
        Some(p) => p,
        None => manage_interactive::ask_password("New password: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation(
                    "reset-operator-password requires --password (or a TTY)".into(),
                )
            })?,
    };
    let hash = crate::tenancy::password::hash(&plain)?;
    let result = rustango::sql::sqlx::query(
        "UPDATE rustango_operators SET password_hash = $1 WHERE username = $2",
    )
    .bind(&hash)
    .bind(&username)
    .execute(pools.registry())
    .await?;
    if result.rows_affected() == 0 {
        return Err(TenancyError::Validation(format!(
            "reset-operator-password: no operator named `{username}`"
        )));
    }
    writeln!(w, "password reset for operator `{username}`")?;
    Ok(())
}

/// Open a short-lived `PgPool` scoped to `slug`'s tenant — schema
/// mode pre-sets `search_path`; database mode reuses the cached
/// per-tenant pool. Shared by `set-superuser` / `reset-password`.
async fn scoped_tenant_pool(
    pools: &TenantPools,
    registry_url: &str,
    slug: &str,
) -> Result<rustango::sql::sqlx::PgPool, TenancyError> {
    let orgs: Vec<crate::tenancy::Org> = crate::tenancy::Org::objects()
        .where_(crate::tenancy::Org::slug.eq(slug.to_owned()))
        .fetch(pools.registry())
        .await?;
    let org = orgs
        .into_iter()
        .next()
        .ok_or_else(|| TenancyError::Validation(format!("no tenant with slug `{slug}`")))?;
    use crate::tenancy::org::StorageMode;
    let mode = StorageMode::parse(&org.storage_mode).map_err(|got| {
        TenancyError::Validation(format!("org `{slug}` has unknown storage_mode `{got}`"))
    })?;
    match mode {
        StorageMode::Schema => {
            let schema = org.schema_name.unwrap_or_else(|| slug.to_owned());
            build_schema_scoped_pool(registry_url, &schema).await
        }
        StorageMode::Database => {
            // Database-mode tenants use the cached pool — clone it
            // so the caller can `.close()` without affecting siblings.
            // Actually the cached pool is shared, so don't close;
            // clone the inner Arc<PgPool> handle instead.
            let tp = pools.pool_for_org(&org).await?;
            Ok(tp.pool().clone())
        }
    }
}

/// Mirror of the migration helper — build a short-lived pool whose
/// connections have `search_path` pre-set. Local copy so manage
/// doesn't need a public reference into [`crate::migrate`].
async fn build_schema_scoped_pool(
    registry_url: &str,
    schema: &str,
) -> Result<rustango::sql::sqlx::PgPool, TenancyError> {
    use crate::sql::sqlx::postgres::PgPoolOptions;
    use std::sync::Arc;
    let schema_owned: Arc<str> = Arc::from(schema);
    let pool = PgPoolOptions::new()
        .max_connections(1)
        .after_connect(move |conn, _meta| {
            let schema = Arc::clone(&schema_owned);
            Box::pin(async move {
                let stmt = format!("SET search_path TO {}, public", quote_ident(&schema));
                rustango::sql::sqlx::query(&stmt).execute(conn).await?;
                Ok(())
            })
        })
        .connect(registry_url)
        .await?;
    Ok(pool)
}