rustango 0.31.2

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Tenant-lifecycle verbs: `create-tenant`, `drop-tenant`,
//! `purge-tenant`, `list-tenants`. Plus their parsers + the
//! database-mode admin-DROP helper.

use std::io::Write;
use std::path::Path;

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

use crate::tenancy::error::TenancyError;
use crate::tenancy::manage::args::{next_value, quote_ident, reject_leading_flag};
use crate::tenancy::manage_interactive;
use crate::tenancy::migrate as tenant_migrate;
use crate::tenancy::org::{Org, StorageMode};
use crate::tenancy::pools::TenantPools;

// ---------- create-tenant ----------

struct CreateTenantArgs {
    slug: String,
    mode: StorageMode,
    display_name: Option<String>,
    database_url: Option<String>,
    schema_name: Option<String>,
    host_pattern: Option<String>,
    port: Option<i32>,
    path_prefix: Option<String>,
    no_migrate: bool,
}

pub(super) async fn create_tenant<W: Write + Send>(
    pools: &TenantPools,
    registry_url: &str,
    dir: &Path,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    let parsed = parse_create_tenant_args(args)?;

    // Reject duplicate slug up front — saves a partial-state mess
    // when CREATE SCHEMA succeeds and the INSERT then fails.
    let existing: Vec<Org> = Org::objects()
        .where_(Org::slug.eq(parsed.slug.clone()))
        .fetch(pools.registry())
        .await?;
    if !existing.is_empty() {
        return Err(TenancyError::Validation(format!(
            "tenant slug `{}` already exists",
            parsed.slug
        )));
    }

    // Compute defaults that depend on the slug + apex env var.
    let host_pattern = parsed.host_pattern.clone().or_else(|| {
        std::env::var("RUSTANGO_APEX_DOMAIN")
            .ok()
            .map(|apex| format!("{}.{apex}", parsed.slug))
    });
    let display_name = parsed
        .display_name
        .clone()
        .unwrap_or_else(|| parsed.slug.clone());
    let schema_name = match parsed.mode {
        StorageMode::Schema => Some(
            parsed
                .schema_name
                .clone()
                .unwrap_or_else(|| parsed.slug.clone()),
        ),
        StorageMode::Database => None,
    };

    if parsed.mode == StorageMode::Database && parsed.database_url.is_none() {
        return Err(TenancyError::Validation(
            "create-tenant --mode database requires --database-url".into(),
        ));
    }

    // Schema-mode: create the schema before inserting the row so
    // a failed INSERT doesn't leave an orphan schema. Idempotent
    // via IF NOT EXISTS.
    if let StorageMode::Schema = parsed.mode {
        let schema = schema_name.as_deref().unwrap_or(&parsed.slug);
        let sql = format!("CREATE SCHEMA IF NOT EXISTS {}", quote_ident(schema));
        rustango::sql::sqlx::query(&sql)
            .execute(pools.registry())
            .await?;
    }

    let mut org = Org {
        id: Auto::default(),
        slug: parsed.slug.clone(),
        display_name,
        storage_mode: parsed.mode.as_str().into(),
        database_url: parsed.database_url.clone(),
        schema_name,
        host_pattern,
        port: parsed.port,
        path_prefix: parsed.path_prefix.clone(),
        active: true,
        created_at: chrono::Utc::now(),
        brand_name: None,
        brand_tagline: None,
        logo_path: None,
        favicon_path: None,
        primary_color: None,
        theme_mode: None,
    };
    org.insert(pools.registry()).await?;
    let id = org.id.get().copied().unwrap_or_default();
    writeln!(
        w,
        "created tenant `{}` (id {id}, mode {})",
        parsed.slug, parsed.mode
    )?;

    // Run tenant migrations against the freshly-provisioned tenant
    // unless --no-migrate.
    if parsed.no_migrate {
        writeln!(w, "  --no-migrate: skipping tenant migrations")?;
        return Ok(());
    }
    writeln!(w, "  applying tenant migrations…")?;
    let report = tenant_migrate::migrate_tenants(pools, dir, registry_url).await?;
    let outcome = report.tenants.iter().find(|t| t.slug == parsed.slug);
    match outcome {
        Some(o) => {
            if let Some(err) = &o.error {
                writeln!(w, "  migration failed: {err}")?;
            } else {
                writeln!(w, "  applied {} migration(s)", o.applied.len())?;
                for m in &o.applied {
                    writeln!(w, "    + {}", m.name)?;
                }
            }
        }
        None => writeln!(w, "  no migrations matched this tenant")?,
    }
    Ok(())
}

fn parse_create_tenant_args(args: &[String]) -> Result<CreateTenantArgs, TenancyError> {
    reject_leading_flag(
        args,
        "create-tenant",
        "slug",
        "create-tenant <slug> [--mode schema|database] [--display-name <s>] \
         [--database-url <url>] [--schema-name <s>] [--host-pattern <s>] \
         [--port <n>] [--path-prefix <s>] [--no-migrate]",
    )?;
    let mut iter = args.iter();
    let slug_arg = iter.next().cloned();
    let slug = match slug_arg {
        Some(s) => s,
        None => manage_interactive::ask("Tenant slug: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation("create-tenant requires a slug positional argument".into())
            })?,
    };
    let mut out = CreateTenantArgs {
        slug,
        mode: StorageMode::Schema,
        display_name: None,
        database_url: None,
        schema_name: None,
        host_pattern: None,
        port: None,
        path_prefix: None,
        no_migrate: false,
    };
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--mode" => {
                let v = next_value(&mut iter, "--mode")?;
                out.mode = StorageMode::parse(&v).map_err(|got| {
                    TenancyError::Validation(format!(
                        "--mode must be `schema` or `database`, got `{got}`"
                    ))
                })?;
            }
            "--display-name" => out.display_name = Some(next_value(&mut iter, "--display-name")?),
            "--database-url" => out.database_url = Some(next_value(&mut iter, "--database-url")?),
            "--schema-name" => out.schema_name = Some(next_value(&mut iter, "--schema-name")?),
            "--host-pattern" => out.host_pattern = Some(next_value(&mut iter, "--host-pattern")?),
            "--port" => {
                let v = next_value(&mut iter, "--port")?;
                out.port = Some(v.parse().map_err(|_| {
                    TenancyError::Validation(format!("--port must be an integer, got `{v}`"))
                })?);
            }
            "--path-prefix" => out.path_prefix = Some(next_value(&mut iter, "--path-prefix")?),
            "--no-migrate" => out.no_migrate = true,
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "create-tenant <slug> [--mode schema|database] [--display-name <s>] \
                     [--database-url <url>] [--schema-name <s>] [--host-pattern <s>] \
                     [--port <n>] [--path-prefix <s>] [--no-migrate]"
                        .into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "create-tenant: unknown argument `{other}`"
                )));
            }
        }
    }
    Ok(out)
}

// ---------- drop-tenant ----------

pub(super) async fn drop_tenant<W: Write + Send>(
    pools: &TenantPools,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    reject_leading_flag(
        args,
        "drop-tenant",
        "slug",
        "drop-tenant <slug> [--confirm <slug>]\n  \
         Soft-delete: sets active=false. Data is preserved.\n  \
         `--confirm` must repeat the slug verbatim — interactive\n  \
         terminals can omit it and answer the prompt instead.",
    )?;
    let mut iter = args.iter();
    let slug_arg = iter.next().cloned();
    let mut confirm: Option<String> = None;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--confirm" => {
                confirm = Some(next_value(&mut iter, "--confirm")?);
            }
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "drop-tenant <slug> [--confirm <slug>]\n  \
                     Soft-delete: sets active=false. Data is preserved.\n  \
                     `--confirm` must repeat the slug verbatim — interactive\n  \
                     terminals can omit it and answer the prompt instead."
                        .into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "drop-tenant: unknown argument `{other}`"
                )));
            }
        }
    }
    let slug = match slug_arg {
        Some(s) => s,
        None => manage_interactive::ask("Tenant slug to drop: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation("drop-tenant requires a slug positional argument".into())
            })?,
    };
    let confirm = match confirm {
        Some(c) => c,
        None => {
            // Interactive confirmation — make the user retype the
            // slug to prove they meant THIS tenant.
            let prompt = format!("Type `{slug}` to confirm soft-delete: ");
            manage_interactive::ask(&prompt)
                .map_err(TenancyError::Io)?
                .ok_or_else(|| {
                    TenancyError::Validation(format!(
                        "drop-tenant requires `--confirm {slug}` (repeat the slug verbatim)"
                    ))
                })?
        }
    };
    if confirm != slug {
        return Err(TenancyError::Validation(format!(
            "drop-tenant: confirmation `{confirm}` does not match slug `{slug}` — aborted"
        )));
    }

    let existing: Vec<Org> = Org::objects()
        .where_(Org::slug.eq(slug.clone()))
        .fetch(pools.registry())
        .await?;
    let Some(org) = existing.into_iter().next() else {
        return Err(TenancyError::Validation(format!(
            "drop-tenant: no tenant with slug `{slug}`"
        )));
    };
    if !org.active {
        writeln!(w, "tenant `{slug}` already inactive — no change")?;
        return Ok(());
    }

    // Soft-delete: UPDATE rustango_orgs SET active = false WHERE id = $1.
    let id = org
        .id
        .get()
        .copied()
        .ok_or_else(|| TenancyError::Validation("dropped Org row has no PK".into()))?;
    let updated = Org::objects()
        .where_(Org::id.eq(id))
        .update()
        .set("active", false)
        .execute(pools.registry())
        .await?;
    if updated == 0 {
        return Err(TenancyError::Validation(format!(
            "drop-tenant: no row updated for id {id} — race condition?"
        )));
    }
    writeln!(
        w,
        "soft-deleted tenant `{slug}` (active=false). Data preserved."
    )?;
    writeln!(
        w,
        "  to hard-delete (drop schema or DB), use `purge-tenant`."
    )?;
    Ok(())
}

// ---------- purge-tenant (v0.6 step 6) ----------

pub(super) async fn purge_tenant<W: Write + Send>(
    pools: &TenantPools,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError> {
    reject_leading_flag(
        args,
        "purge-tenant",
        "slug",
        "purge-tenant <slug> [--confirm <slug>] [--purge-database]\n  \
         HARD-DELETE. Schema-mode: DROP SCHEMA <slug> CASCADE.\n  \
         Database-mode: refuses unless `--purge-database` is also\n  \
         passed; with it, runs `DROP DATABASE` against an admin\n  \
         connection. The Org row is deleted in both cases.\n  \
         Data is unrecoverable. Use `drop-tenant` for soft-delete.\n  \
         `--confirm` must repeat the slug verbatim — interactive\n  \
         terminals can omit it and answer the prompt instead.",
    )?;
    let mut iter = args.iter();
    let slug_arg = iter.next().cloned();
    let mut confirm: Option<String> = None;
    let mut purge_database = false;
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--confirm" => {
                confirm = Some(next_value(&mut iter, "--confirm")?);
            }
            "--purge-database" => purge_database = true,
            "--help" | "-h" => {
                return Err(TenancyError::Validation(
                    "purge-tenant <slug> [--confirm <slug>] [--purge-database]\n  \
                     HARD-DELETE. Schema-mode: DROP SCHEMA <slug> CASCADE.\n  \
                     Database-mode: refuses unless `--purge-database` is also\n  \
                     passed; with it, runs `DROP DATABASE` against an admin\n  \
                     connection. The Org row is deleted in both cases.\n  \
                     Data is unrecoverable. Use `drop-tenant` for soft-delete.\n  \
                     `--confirm` must repeat the slug verbatim — interactive\n  \
                     terminals can omit it and answer the prompt instead."
                        .into(),
                ));
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "purge-tenant: unknown argument `{other}`"
                )));
            }
        }
    }
    let slug = match slug_arg {
        Some(s) => s,
        None => manage_interactive::ask("Tenant slug to PURGE: ")
            .map_err(TenancyError::Io)?
            .ok_or_else(|| {
                TenancyError::Validation("purge-tenant requires a slug positional argument".into())
            })?,
    };
    let confirm = match confirm {
        Some(c) => c,
        None => {
            // Interactive confirmation — make the operator retype the
            // slug to prove they meant THIS tenant. Mirrors drop-tenant
            // but the consequence is hard-delete, so the message is louder.
            let prompt = format!("HARD-DELETE: type `{slug}` to confirm permanent deletion: ");
            manage_interactive::ask(&prompt)
                .map_err(TenancyError::Io)?
                .ok_or_else(|| {
                    TenancyError::Validation(format!(
                        "purge-tenant requires `--confirm {slug}` (repeat the slug verbatim)"
                    ))
                })?
        }
    };
    if confirm != slug {
        return Err(TenancyError::Validation(format!(
            "purge-tenant: confirmation `{confirm}` does not match slug `{slug}` — aborted"
        )));
    }

    let existing: Vec<Org> = Org::objects()
        .where_(Org::slug.eq(slug.clone()))
        .fetch(pools.registry())
        .await?;
    let Some(org) = existing.into_iter().next() else {
        return Err(TenancyError::Validation(format!(
            "purge-tenant: no tenant with slug `{slug}`"
        )));
    };

    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.clone().unwrap_or_else(|| slug.clone());
            let sql = format!("DROP SCHEMA IF EXISTS {} CASCADE", quote_ident(&schema));
            rustango::sql::sqlx::query(&sql)
                .execute(pools.registry())
                .await?;
            writeln!(w, "purged tenant `{slug}` (dropped schema `{schema}`)")?;
        }
        StorageMode::Database => {
            if !purge_database {
                return Err(TenancyError::Validation(format!(
                    "tenant `{slug}` is database-mode — `DROP DATABASE` is unrecoverable. \
                     Pass `--purge-database` to confirm you want the DB dropped, or use \
                     `drop-tenant` for soft-delete."
                )));
            }
            // Resolve the URL through the secrets resolver so vault-
            // backed orgs purge correctly. Then close & drop the
            // cached pool — DROP DATABASE refuses while connections
            // are open.
            let url = pools.resolved_database_url(&org).await?;
            pools.invalidate(&slug).await;
            drop_database_at(&url, w).await?;
            writeln!(w, "purged tenant `{slug}` (dropped dedicated database)")?;
        }
    }

    // DELETE the Org row. Use a raw query so we don't depend on a
    // model-level delete API (rustango doesn't ship one yet).
    let id = org
        .id
        .get()
        .copied()
        .ok_or_else(|| TenancyError::Validation("purge-tenant: Org row has no PK".into()))?;
    let result = rustango::sql::sqlx::query("DELETE FROM rustango_orgs WHERE id = $1")
        .bind(id)
        .execute(pools.registry())
        .await?;
    if result.rows_affected() == 0 {
        return Err(TenancyError::Validation(format!(
            "purge-tenant: no Org row deleted for id {id} — race condition?"
        )));
    }
    writeln!(w, "  removed Org row (id {id})")?;
    Ok(())
}

/// Connect to the same Postgres server as `tenant_url` but switch to
/// the `postgres` admin database (DROP DATABASE can't run from a
/// connection to the database being dropped). Issue the DROP, then
/// close the admin connection.
async fn drop_database_at<W: Write + Send>(
    tenant_url: &str,
    w: &mut W,
) -> Result<(), TenancyError> {
    use crate::sql::sqlx::postgres::PgConnectOptions;
    use crate::sql::sqlx::ConnectOptions;
    use std::str::FromStr;

    let opts = PgConnectOptions::from_str(tenant_url).map_err(|e| {
        TenancyError::Validation(format!(
            "purge-tenant: cannot parse database_url `{tenant_url}`: {e}"
        ))
    })?;
    let dbname = opts.get_database().ok_or_else(|| {
        TenancyError::Validation(
            "purge-tenant: database_url is missing the database name — \
             can't determine what to DROP DATABASE"
                .into(),
        )
    })?;
    if dbname.eq_ignore_ascii_case("postgres")
        || dbname.eq_ignore_ascii_case("template0")
        || dbname.eq_ignore_ascii_case("template1")
    {
        return Err(TenancyError::Validation(format!(
            "purge-tenant: refusing to DROP DATABASE `{dbname}` (Postgres system database)"
        )));
    }
    let dbname = dbname.to_owned();
    let admin_opts = opts.clone().database("postgres");
    let mut admin = admin_opts.connect().await?;
    let sql = format!("DROP DATABASE IF EXISTS {}", quote_ident(&dbname));
    writeln!(w, "  issuing {sql}")?;
    rustango::sql::sqlx::query(&sql).execute(&mut admin).await?;
    Ok(())
}

// ---------- list-tenants ----------

pub(super) async fn list_tenants<W: Write + Send>(
    pools: &TenantPools,
    w: &mut W,
) -> Result<(), TenancyError> {
    let orgs: Vec<Org> = Org::objects().fetch(pools.registry()).await?;
    if orgs.is_empty() {
        writeln!(w, "(no tenants)")?;
        return Ok(());
    }
    writeln!(
        w,
        "{:<24} {:<10} {:<32} {:<8} created_at",
        "slug", "mode", "host_pattern", "active"
    )?;
    writeln!(w, "{}", "-".repeat(80))?;
    for o in &orgs {
        writeln!(
            w,
            "{:<24} {:<10} {:<32} {:<8} {}",
            truncate(&o.slug, 24),
            o.storage_mode,
            o.host_pattern.as_deref().unwrap_or("-"),
            o.active,
            o.created_at.format("%Y-%m-%d %H:%M:%SZ"),
        )?;
    }
    Ok(())
}

fn truncate(s: &str, n: usize) -> String {
    if s.len() <= n {
        s.to_owned()
    } else {
        format!("{}", &s[..n.saturating_sub(1)])
    }
}