rustango 0.61.13

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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//! Tenant provisioning + management subcommands.
//!
//! Composes with `crate::migrate::manage::run` — recognizes the
//! tenancy-specific verbs (`create-tenant`, `drop-tenant`,
//! `purge-tenant`, `list-tenants`, `migrate-tenants`,
//! `migrate-registry`, `init-tenancy`, `create-operator`,
//! `create-user`, `run-server`, scope-aware `migrate`) and delegates
//! everything else to the standard single-tenant runner using the
//! registry pool.
//!
//! ## User wiring
//!
//! ```ignore
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let registry_url = std::env::var("DATABASE_URL")?;
//!     let pool = rustango::sql::sqlx::PgPool::connect(&registry_url).await?;
//!     let pools = crate::tenancy::TenantPools::new(pool);
//!     let dir = std::path::Path::new("./migrations");
//!     crate::tenancy::manage::run(
//!         &pools,
//!         &registry_url,
//!         dir,
//!         std::env::args().skip(1),
//!     ).await?;
//!     Ok(())
//! }
//! ```
//!
//! ## Crate-internal layout
//!
//! - [`tenants`] — `create-tenant`, `drop-tenant`, `purge-tenant`,
//!   `list-tenants` plus the database-mode admin-DROP helper.
//! - [`users`] — `create-operator`, `create-user`, plus the
//!   schema-scoped pool builder used to land tenant inserts.
//! - [`migrations`] — `init-tenancy`, `migrate`, `migrate-registry`,
//!   `migrate-tenants` and the tenant migration report formatter.
//! - [`server`] — `run-server` (thin wrapper around
//!   [`super::server::run`]).
//! - [`args`] — shared positional / flag parsing helpers.

// Agent / skill verbs are MCP-only (see `super::agents`, gated the same way).
#[cfg(feature = "mcp")]
mod agents;
mod args;
mod audit;
mod data;
mod db_servers;
mod edit;
mod flush;
mod hosts;
mod inspect;
mod menu;
#[cfg(feature = "postgres")]
mod migrate_storage;
mod migrations;
mod operators;
mod reseal;
mod roles;
mod scaffold;
mod server;
#[cfg(feature = "sso")]
mod sso_check;
mod tenants;
mod users;
mod wizard;

/// Typed Rust API for tenancy provisioning — `create_tenant_if_missing`,
/// `create_operator_if_missing`, `create_user_if_missing`, `find_org`.
/// Use these from `Builder::seed_with` closures and other in-process
/// callers; the verb dispatcher
/// [`run_with_writer`](crate::tenancy::manage::run_with_writer) is the
/// CLI surface.
pub mod api;

use std::io::{self, Write};
use std::path::Path;

use super::error::TenancyError;
use super::pools::TenantPools;

/// `Cli` runs it before any pool exists.
#[cfg(feature = "manage")]
pub(crate) use scaffold::startapp_cmd as startapp;

/// Function pointer for the bootstrap initializer used by the
/// `init-tenancy` verb. Defaults to
/// [`crate::tenancy::bootstrap::init_tenancy`]; override via
/// [`run_with_init`] / [`run_with_writer_and_init`] to swap in a
/// custom [`crate::tenancy::TenantUserModel`] (typically threaded
/// from [`crate::manage::Cli::user_model`]).
pub type InitTenancyFn = fn(&Path) -> Result<super::bootstrap::InitTenancyReport, TenancyError>;

/// Dispatch entrypoint. Recognizes tenancy verbs and delegates the
/// rest to `crate::migrate::manage::run`.
///
/// `dir` is the migrations directory (same as the underlying
/// rustango-migrate runner). `registry_url` is needed for schema-
/// mode tenant migrations + tenant pool building; supply the same
/// value the registry pool was built from.
///
/// # Errors
/// Either a [`TenancyError`] from a tenancy verb, or a wrapped
/// `crate::migrate::MigrateError` from the delegated call.
pub async fn run<DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: impl IntoIterator<Item = String>,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let mut stdout = io::stdout();
    run_with_writer(pools, registry_url, dir, args, &mut stdout).await
}

/// Like [`run`] but with a custom bootstrap initializer — wires a
/// [`crate::tenancy::TenantUserModel`] override through to the
/// `init-tenancy` verb. Other verbs ignore `init_fn`.
///
/// # Errors
/// As [`run`].
pub async fn run_with_init<DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: impl IntoIterator<Item = String>,
    init_fn: InitTenancyFn,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let mut stdout = io::stdout();
    run_with_writer_and_init(pools, registry_url, dir, args, &mut stdout, init_fn).await
}

/// Same as [`run`] but writes user-facing output to `writer` —
/// useful for tests.
///
/// # Errors
/// As [`run`].
pub async fn run_with_writer<W: Write + Send, DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: impl IntoIterator<Item = String>,
    writer: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    run_with_writer_and_init(
        pools,
        registry_url,
        dir,
        args,
        writer,
        super::bootstrap::init_tenancy,
    )
    .await
}

/// Full-bore variant: custom writer **and** custom bootstrap
/// initializer. The other variants are ergonomic wrappers around
/// this one.
///
/// # Errors
/// As [`run`].
pub async fn run_with_writer_and_init<W: Write + Send, DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: impl IntoIterator<Item = String>,
    writer: &mut W,
    init_fn: InitTenancyFn,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    // Boxed: inline, dispatch's state overflows a 2 MiB test thread in debug builds.
    Box::pin(dispatch(
        pools,
        registry_url,
        dir,
        args.into_iter().collect(),
        writer,
        init_fn,
    ))
    .await
}

/// What `Cli` knows about the deployment that a verb cannot see.
#[derive(Clone, Default)]
pub(crate) struct CliFacts {
    /// `with_tenant_provisioning` was called.
    pub(crate) provisioning: bool,
    /// `Cli::brand_storage`, for the verbs that delete brand files.
    pub(crate) brand_storage: Option<crate::storage::BoxedStorage>,
}

/// [`run_with_writer_and_init`] with the `Cli`'s [`CliFacts`].
#[cfg(feature = "manage")]
pub(crate) async fn run_from_cli<W: Write + Send, DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: Vec<String>,
    writer: &mut W,
    init_fn: InitTenancyFn,
    facts: CliFacts,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    Box::pin(dispatch_with(
        pools,
        registry_url,
        dir,
        args,
        writer,
        init_fn,
        facts,
    ))
    .await
}

/// One verb, dispatched. Split out so `menu` can run a chosen verb through
/// the same match rather than shelling out or duplicating the table.
pub(super) async fn dispatch<W: Write + Send, DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: Vec<String>,
    writer: &mut W,
    init_fn: InitTenancyFn,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    dispatch_with(
        pools,
        registry_url,
        dir,
        args,
        writer,
        init_fn,
        CliFacts::default(),
    )
    .await
}

async fn dispatch_with<W: Write + Send, DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    args: Vec<String>,
    writer: &mut W,
    init_fn: InitTenancyFn,
    facts: CliFacts,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let cmd = args.first().map_or("", String::as_str);

    match cmd {
        "" | "help" | "--help" | "-h" => {
            write_help(writer)?;
            Ok(())
        }
        "create-tenant" => {
            tenants::create_tenant(pools, registry_url, dir, &args[1..], writer).await
        }
        "test-tenant-connection" => tenants::test_tenant_connection(&args[1..], writer).await,
        "drop-tenant" => tenants::drop_tenant(pools, &args[1..], writer).await,
        "purge-tenant" => {
            tenants::purge_tenant(pools, &args[1..], writer, facts.brand_storage.clone()).await
        }
        "rotate-tenant-password" => {
            tenants::rotate_tenant_password(pools, &args[1..], writer).await
        }
        "list-tenants" => {
            args::no_args(&args[1..], "list-tenants")?;
            tenants::list_tenants(pools, writer).await
        }
        // #1344 — routing and display config were console-only to change.
        "edit-tenant" => edit::edit_tenant(pools, &args[1..], writer).await,
        "reseal-tenant-secrets" => reseal::reseal_tenant_secrets(pools, &args[1..], writer).await,
        // #1344 — the console has bound extra hostnames since #1318; these
        // give a deploy hook and a browser-less box the same reach.
        "list-hosts" => hosts::list_hosts(pools, &args[1..], writer).await,
        "add-host" => hosts::add_host(pools, &args[1..], writer).await,
        "remove-host" => hosts::remove_host(pools, &args[1..], writer).await,
        "set-host-enabled" => hosts::set_host_enabled(pools, &args[1..], writer).await,
        "add-db-server" => db_servers::add_db_server(pools, &args[1..], writer).await,
        "edit-db-server" => db_servers::edit_db_server(pools, &args[1..], writer).await,
        "list-db-servers" => db_servers::list_db_servers(pools, &args[1..], writer).await,
        "test-db-server" => db_servers::test_db_server(pools, &args[1..], writer).await,
        "remove-db-server" => db_servers::remove_db_server(pools, &args[1..], writer).await,
        "prewarm-pools" => {
            // v0.27.7 (#60) — eagerly build pools for every active
            // database-mode tenant. Useful as a post-deploy hook
            // after credential rotation, or to validate that all
            // tenants are reachable before flipping a load balancer.
            args::no_args(&args[1..], "prewarm-pools")?;
            let report = pools.prewarm_database_tenants().await?;
            writeln!(
                writer,
                "prewarm: {} active tenants — warmed {}, failed {}, skipped (cap) {}",
                report.total_active, report.warmed, report.failed, report.skipped_cap
            )?;
            migrations::tenant_failures(report.failed, report.total_active)
        }
        "migrate-tenants" => {
            migrations::migrate_tenants_cmd(pools, registry_url, dir, &args[1..], writer).await
        }
        "migrate-registry" => {
            migrations::migrate_registry_cmd(pools, dir, &args[1..], writer).await
        }
        #[cfg(feature = "postgres")]
        "migrate-tenant-storage" => {
            // PG-only: uses pg_dump | psql + schema-mode dispatch.
            // Downcast through `Any` so the generic dispatcher path
            // can still compile on multi-backend builds.
            let pg_pools = (pools as &dyn std::any::Any)
                .downcast_ref::<TenantPools<sqlx::Postgres>>()
                .ok_or_else(|| {
                    TenancyError::Validation(
                        "migrate-tenant-storage is Postgres-only (uses pg_dump | psql + \
                         schema-mode dispatch). Re-run with a postgres:// DATABASE_URL."
                            .into(),
                    )
                })?;
            migrate_storage::migrate_tenant_storage_cmd(pg_pools, registry_url, &args[1..], writer)
                .await
        }
        #[cfg(not(feature = "postgres"))]
        "migrate-tenant-storage" => Err(TenancyError::Validation(
            "migrate-tenant-storage requires the `postgres` feature (uses pg_dump | psql + \
             schema-mode is PG-only)"
                .into(),
        )),
        "create-operator" => users::create_operator_cmd(pools, &args[1..], writer).await,
        // #1344 — seeing who exists, and turning one off, were console-only.
        "list-operators" => operators::list_operators(pools, &args[1..], writer).await,
        "set-operator-active" => operators::set_operator_active(pools, &args[1..], writer).await,
        #[cfg(feature = "totp")]
        "reset-operator-totp" => operators::reset_operator_totp(pools, &args[1..], writer).await,
        // #1344 — the console renders all three; nothing printed them, so an
        // incident question needed a browser or a SQL client.
        "list-runs" => inspect::list_runs(pools, &args[1..], writer).await,
        "show-run" => inspect::show_run(pools, &args[1..], writer).await,
        "audit-log" => inspect::audit_log(pools, &args[1..], writer).await,
        "create-user" => users::create_user_cmd(pools, registry_url, &args[1..], writer).await,
        "create-superuser" => {
            users::create_superuser_cmd(pools, registry_url, &args[1..], writer).await
        }
        "set-superuser" => users::set_superuser_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "passkey")]
        "revoke-passkey" => {
            users::revoke_passkey_cmd(pools, registry_url, &args[1..], writer).await
        }
        "reset-password" => {
            users::reset_password_cmd(pools, registry_url, &args[1..], writer).await
        }
        "set-password-link" => tenants::set_password_link(pools, &args[1..], writer).await,
        "reset-operator-password" => {
            users::reset_operator_password_cmd(pools, &args[1..], writer).await
        }
        "change-password" => {
            users::change_password_cmd(pools, registry_url, &args[1..], writer).await
        }
        "change-operator-password" => {
            users::change_operator_password_cmd(pools, &args[1..], writer).await
        }
        "run-server" | "runserver" => {
            server::run_server_cmd(pools, registry_url, &args[1..], writer).await
        }
        "init-tenancy" => migrations::init_tenancy_cmd_with(dir, writer, init_fn),
        "wizard" | "init" => {
            // Interactive setup wizard (roadmap #2, v0.30.14).
            // Reads from stdin, writes to the same writer the
            // dispatcher uses. `init` is an alias the muscle
            // memory of `cargo init` users will reach for.
            //
            // `SharedStdin`, not `stdin.lock()`: this calls verbs that
            // prompt for themselves, and holding the lock across that
            // deadlocks (#1360).
            let mut reader = crate::manage_interactive::SharedStdin;
            wizard::wizard_cmd(pools, registry_url, dir, init_fn, &mut reader, writer).await
        }
        // The wizard above is a linear first-run setup; this is the standing
        // list of everything you can do afterwards (#1345).
        "menu" | "actions" => {
            // Off a terminal there is nobody to answer, and rendering the
            // menu to a log while exiting 0 looks like success (#1357).
            if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
                return Err(TenancyError::Validation(
                    "`menu` needs a terminal — run a verb directly, or `--help` for the list"
                        .into(),
                ));
            }
            let mut reader = crate::manage_interactive::SharedStdin;
            menu::menu_cmd(pools, registry_url, dir, init_fn, &mut reader, writer).await
        }
        // Intercepted before fall-through: tenancy ships its own
        // manage.rs template in `--with-manage-bin`, wiring
        // `crate::tenancy::manage::run` instead of the single-tenant
        // dispatcher. Plain models/views/urls files are identical
        // across both crates, so the heavy lifting still runs through
        // `rustango::migrate::scaffold::startapp`.
        "audit-cleanup" => audit::audit_cleanup_cmd(pools, &args[1..], writer).await,
        // The fall-through flush is scope-blind and ran on the registry pool (#2284).
        "flush" => flush::flush_cmd(pools, &args[1..], writer).await,
        // The fall-through read and wrote every model on the registry pool.
        "dumpdata" => data::data_cmd(pools, data::Verb::Dump, &args[1..], writer).await,
        "loaddata" => data::data_cmd(pools, data::Verb::Load, &args[1..], writer).await,
        // `public` holds the registry here; --clean would drop every org with it.
        "db:restore" if args[1..].iter().any(|a| a == "--clean") => Err(TenancyError::Validation(
            "db:restore --clean is refused in a tenancy project: schema `public` is the registry"
                .into(),
        )),
        "create-role" => roles::create_role_cmd(pools, &args[1..], writer).await,
        "list-roles" => roles::list_roles_cmd(pools, &args[1..], writer).await,
        "assign-role" => roles::assign_role_cmd(pools, &args[1..], writer).await,
        "revoke-role" => roles::revoke_role_cmd(pools, &args[1..], writer).await,
        "grant-perm" => roles::grant_perm_cmd(pools, &args[1..], writer).await,
        "revoke-perm" => roles::revoke_perm_cmd(pools, &args[1..], writer).await,
        "create-api-key" => roles::create_api_key_cmd(pools, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "create-agent" => agents::create_agent_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "rotate-agent-secret" => {
            agents::rotate_agent_secret_cmd(pools, registry_url, &args[1..], writer).await
        }
        #[cfg(feature = "mcp")]
        "list-agents" => agents::list_agents_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "create-skill" => agents::create_skill_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "grant-skill" => agents::grant_skill_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "revoke-skill" => agents::revoke_skill_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "list-skills" => agents::list_skills_cmd(pools, registry_url, &args[1..], writer).await,
        #[cfg(feature = "mcp")]
        "create-user-key" => {
            agents::create_user_key_cmd(pools, registry_url, &args[1..], writer).await
        }
        #[cfg(feature = "mcp")]
        "list-user-keys" => {
            agents::list_user_keys_cmd(pools, registry_url, &args[1..], writer).await
        }
        #[cfg(feature = "mcp")]
        "revoke-user-key" => {
            agents::revoke_user_key_cmd(pools, registry_url, &args[1..], writer).await
        }
        #[cfg(feature = "mcp")]
        "map-skill-permission" => {
            agents::map_skill_permission_cmd(pools, registry_url, &args[1..], writer).await
        }
        #[cfg(feature = "mcp")]
        "unmap-skill-permission" => {
            agents::unmap_skill_permission_cmd(pools, registry_url, &args[1..], writer).await
        }
        // The SSO providers live per tenant, which the registry pool can't see (#2359).
        // Tenant-scoped files are compared with each tenant's ledger.
        "check" => rustango::migrate::manage::check_cmd_with(
            &pools.registry_pool(),
            dir,
            &args[1..],
            writer,
            Some(rustango::migrate::manage::TenancyCheck {
                deploy: tenancy_deploy_findings(pools, facts),
                ledgers: migrations::active_tenant_ledgers(pools),
            }),
        )
        .await
        .map_err(TenancyError::Migrate),
        // Tenant-scoped migrations are recorded in the tenant ledgers (#2393).
        "forget-pending" => rustango::migrate::manage::forget_pending_cmd_with(
            &pools.registry_pool(),
            dir,
            &args[1..],
            writer,
            async {
                let [project] =
                    migrations::tenant_ledgers(pools, [rustango::migrate::LEDGER_TABLE]).await?;
                Ok(project)
            },
        )
        .await
        .map_err(TenancyError::Migrate),
        "showmigrations" | "status" => migrations::showmigrations_cmd(pools, dir, writer).await,
        // Tenant-scoped migrations live in the tenant ledgers, not the registry's.
        "downgrade" => migrations::downgrade_cmd(pools, dir, &args[1..], writer).await,
        "seed-permissions" => roles::seed_permissions_cmd(pools, &args[1..], writer).await,
        "startapp" => scaffold::startapp_cmd(&args[1..], writer),
        // Plain `migrate` is scope-aware here — registry-scoped
        // migrations apply to the registry pool first, then tenant-
        // scoped ones fan out across active orgs. Direct fall-through
        // to `rustango::migrate::manage` (which is scope-blind) would
        // apply tenant migrations to the registry pool, a real
        // footgun. `migrate-registry` / `migrate-tenants` stay
        // available for fine-grained control.
        "migrate" => {
            migrations::migrate_all_cmd(pools, registry_url, dir, &args[1..], writer).await
        }
        // Everything else (makemigrations, sqlmigrate,
        // …) is registry-scoped and delegates to the standard
        // single-tenant runner.
        // v0.38 — `manage::run_with_writer` now accepts `&crate::sql::Pool`
        // (instead of `&PgPool`), so we route through the tri-dialect
        // `registry_pool()` accessor that returns the backend-agnostic
        // enum form.
        _ => rustango::migrate::manage::run_with_writer(&pools.registry_pool(), dir, args, writer)
            .await
            .map_err(TenancyError::Migrate),
    }
}

/// Render the curated help text for `cargo run` (or
/// equivalent). Covers every tenancy verb with a brief description +
/// the most common flags, then the registry-scoped verbs that fall
/// through to `rustango::migrate::manage`.
///
/// Public so generated `manage.rs` binaries can short-circuit the
/// `help` / `--help` / `-h` / no-args case **before** connecting to
/// Postgres — otherwise `cargo run -- help` would error
/// with "missing DATABASE_URL" and the user couldn't see the help.
///
/// # Errors
/// Returns [`TenancyError::Io`] for a failed write — should not happen
/// against `std::io::stdout()`.
pub fn write_help<W: Write>(w: &mut W) -> Result<(), TenancyError> {
    writeln!(w, "rustango manage CLI — tenancy-aware dispatcher")?;
    writeln!(w)?;
    writeln!(w, "USAGE:")?;
    writeln!(w, "  cargo run -- <verb> [args]")?;
    writeln!(w)?;
    writeln!(w, "TENANT MANAGEMENT:")?;
    writeln!(
        w,
        "  create-tenant <slug> [--display-name <s>] [--mode schema|database]"
    )?;
    writeln!(
        w,
        "                       [--host-pattern <s>] [--database-url <s> | --server <name>] [--no-migrate]"
    )?;
    writeln!(
        w,
        "                       [--admin-email <e> [--admin-username <u>]]  first admin; prints a set-password link"
    )?;
    writeln!(
        w,
        "                       [--resume]  finish a tenant whose migrations failed (left inactive)"
    )?;
    writeln!(
        w,
        "  test-tenant-connection <url> [--no-write-probe] [--timeout <secs>]"
    )?;
    writeln!(
        w,
        "                       Provision a new tenant. Schema mode (default) gives the"
    )?;
    writeln!(
        w,
        "                       tenant its own Postgres schema; database mode points at"
    )?;
    writeln!(
        w,
        "                       a separate DB: an existing one via --database-url, or a new"
    )?;
    writeln!(
        w,
        "                       one with its own login on a saved server via --server."
    )?;
    writeln!(w, "  drop-tenant   <slug> [--confirm <slug>]")?;
    writeln!(
        w,
        "                       Soft-delete (active=false). Data preserved."
    )?;
    writeln!(
        w,
        "  purge-tenant  <slug> [--confirm <slug>] [--purge-database]"
    )?;
    writeln!(
        w,
        "                       HARD-delete: drops schema (or DB with --purge-database)."
    )?;
    writeln!(w, "  rotate-tenant-password <slug>")?;
    writeln!(
        w,
        "                       New password for a login made on a saved server."
    )?;
    writeln!(
        w,
        "  list-tenants         Print every Org row in the registry."
    )?;
    writeln!(
        w,
        "  edit-tenant <slug> [--display-name <s>] [--host-pattern <h>]"
    )?;
    writeln!(
        w,
        "                     [--path-prefix <p>] [--port <n>] [--database-url <u>]"
    )?;
    writeln!(
        w,
        "                     [--activate | --deactivate] [--clear <field>]"
    )?;
    writeln!(
        w,
        "  reseal-tenant-secrets [--apply]  Re-seal stored tenant URLs with the current key (dry run without --apply)."
    )?;
    writeln!(
        w,
        "                       Change routing and display config. Only the fields you"
    )?;
    writeln!(
        w,
        "                       name are touched; --clear empties one. Rotating the URL"
    )?;
    writeln!(w, "                       evicts the tenant's pool.")?;
    writeln!(w)?;
    writeln!(w, "INSPECTION (read-only):")?;
    writeln!(
        w,
        "  list-runs [--limit N] [--kind provision|migrate|purge|rotate_password] [--state <s>]"
    )?;
    writeln!(
        w,
        "                       Recent provisioning and migration runs, newest first."
    )?;
    writeln!(
        w,
        "  show-run <id>        One run's header and every step it recorded."
    )?;
    writeln!(
        w,
        "  audit-log [--limit N] [--table <t>] [--pk <v>] [--operation <o>] [--source <s>]"
    )?;
    writeln!(
        w,
        "                       The registry's audit trail — who changed what, and when."
    )?;
    writeln!(w)?;
    writeln!(w, "HOSTNAMES:")?;
    writeln!(
        w,
        "  list-hosts <slug>    Every hostname the tenant answers on, base first."
    )?;
    writeln!(w, "  add-host <slug> <hostname>")?;
    writeln!(
        w,
        "                       Bind an extra hostname. Rejected if another tenant"
    )?;
    writeln!(w, "                       already claims it.")?;
    writeln!(w, "  remove-host <slug> <hostname>")?;
    writeln!(
        w,
        "                       Unbind one. The base host cannot be removed here —"
    )?;
    writeln!(w, "                       change --host-pattern instead.")?;
    writeln!(w, "  set-host-enabled <slug> <hostname> --on|--off")?;
    writeln!(
        w,
        "                       Park a host without losing the record (DNS in flight,"
    )?;
    writeln!(w, "                       domain being retired).")?;
    writeln!(w)?;
    writeln!(w, "DATABASE SERVERS:")?;
    writeln!(
        w,
        "  add-db-server <name> --host <h> [--port <n>] --user <u> [--tls <mode>, default require]"
    )?;
    writeln!(
        w,
        "                [--maintenance-db <db>] [--sqlite-dir <dir>] [--password-env <VAR> | --no-password]"
    )?;
    writeln!(
        w,
        "                       Save a server's admin login; the password is asked hidden"
    )?;
    writeln!(
        w,
        "                       and stored sealed (needs RUSTANGO_SECRET_KEY)."
    )?;
    writeln!(w, "  list-db-servers      Saved servers, without secrets.")?;
    writeln!(
        w,
        "  test-db-server <name>  Log in and report the admin login's rights."
    )?;
    writeln!(
        w,
        "  edit-db-server <name> [same flags] [--prompt-password | --clear-password] [--on|--off]"
    )?;
    writeln!(
        w,
        "  remove-db-server <name>  Refused while a tenant's database is on it."
    )?;
    writeln!(w)?;
    writeln!(w, "USER / OPERATOR MANAGEMENT:")?;
    writeln!(
        w,
        "  create-operator <username> [--password <p> | --generate]"
    )?;
    writeln!(
        w,
        "                       Operator-level account; signs into the apex /login."
    )?;
    writeln!(
        w,
        "  list-operators       Every operator, with active state and creation date."
    )?;
    writeln!(w, "  set-operator-active <username> --on|--off")?;
    writeln!(
        w,
        "                       Turn an operator's access off or back on. Refuses to"
    )?;
    writeln!(
        w,
        "                       deactivate the last active one — that would lock"
    )?;
    writeln!(w, "                       everyone out of the console.")?;
    writeln!(w, "  reset-operator-totp <username>")?;
    writeln!(
        w,
        "                       Remove an operator's two-factor device (lost phone)."
    )?;
    writeln!(
        w,
        "  create-user <slug> <username> [--password <p> | --generate] [--superuser]"
    )?;
    writeln!(
        w,
        "                       Tenant-scoped user; signs into <slug>.<apex>{}.",
        crate::tenancy::RouteConfig::default().login_url
    )?;
    writeln!(w, "  create-superuser <slug> <username> [--password <p>]")?;
    writeln!(
        w,
        "                       Tenant-scoped superuser (alias for create-user --superuser)."
    )?;
    writeln!(w, "  set-superuser <slug> <username> [--on|--off]")?;
    writeln!(
        w,
        "                       Promote / demote an existing tenant user."
    )?;
    #[cfg(feature = "passkey")]
    writeln!(
        w,
        "  revoke-passkey <slug> <username> [--credential <id>]\n                       \
         Delete one passkey of a tenant user, or all of them."
    )?;
    writeln!(
        w,
        "  reset-password <slug> <username> [--password <p> | --generate]"
    )?;
    writeln!(
        w,
        "                       Reset a tenant user's password without their old one."
    )?;
    writeln!(w, "  set-password-link <slug> <username>")?;
    writeln!(
        w,
        "                       A single-use link for the user to set their own password."
    )?;
    writeln!(
        w,
        "  reset-operator-password <username> [--password <p> | --generate]"
    )?;
    writeln!(
        w,
        "                       Reset an operator's password without their old one."
    )?;
    writeln!(
        w,
        "  change-password <slug> <username> [--current <p> | --current-stdin] [--password <p> | --generate]"
    )?;
    writeln!(
        w,
        "                       Rotate a tenant user's password; verifies current first."
    )?;
    writeln!(
        w,
        "  change-operator-password <username> [--current <p> | --current-stdin] [--password <p> | --generate]"
    )?;
    writeln!(
        w,
        "                       Rotate an operator's password; verifies current first."
    )?;
    writeln!(w)?;
    writeln!(w, "QUICK START:")?;
    writeln!(
        w,
        "  wizard | init        Interactive setup — walks you from a fresh project to"
    )?;
    writeln!(
        w,
        "                       a working tenant + operator + tenant superuser through"
    )?;
    writeln!(
        w,
        "                       prompts. Each step is opt-in (press n to skip)."
    )?;
    writeln!(
        w,
        "  menu | actions       Numbered list of the common verbs. Asks only for what"
    )?;
    writeln!(
        w,
        "                       the verb won't ask itself, echoes the equivalent"
    )?;
    writeln!(
        w,
        "                       command line, then runs it and comes back."
    )?;
    writeln!(w)?;
    writeln!(w, "MIGRATIONS:")?;
    writeln!(
        w,
        "  init-tenancy         No-op, kept so old scripts don't break. Framework tables\n\
         \x20                      are generated from the models and applied by `migrate`."
    )?;
    writeln!(
        w,
        "  makemigrations       Diff models against latest snapshot, emit a new JSON file."
    )?;
    writeln!(
        w,
        "  migrate              Apply registry-scoped, then tenant-scoped, migrations."
    )?;
    writeln!(
        w,
        "  migrate --fake <name>  Insert <name> into registry ledger WITHOUT running its SQL"
    )?;
    writeln!(
        w,
        "                         (recovery: \"relation X already exists\" 42P07 errors)."
    )?;
    writeln!(
        w,
        "  migrate-registry     Apply registry-scoped migrations only."
    )?;
    writeln!(
        w,
        "  migrate-tenants      Apply tenant-scoped migrations to every active org."
    )?;
    writeln!(
        w,
        "  prewarm-pools        Eagerly build pools for every active database-mode tenant"
    )?;
    writeln!(
        w,
        "                       (drops first-request latency on the hot path)."
    )?;
    writeln!(
        w,
        "  migrate-tenant-storage <slug> --to schema|database [--database-url <s>] [--schema-name <s>] [--allow-extension <name>]... [--drain-secs <n>] [--dry-run]"
    )?;
    writeln!(
        w,
        "                       Move a tenant between storage modes via pg_dump → psql."
    )?;
    writeln!(
        w,
        "  showmigrations       List which migrations are applied / pending."
    )?;
    writeln!(
        w,
        "  downgrade [N | <target>] [--tenant <slug> | --all-tenants [--yes]]"
    )?;
    writeln!(
        w,
        "                       Roll back the last N migrations (default 1), or those after"
    )?;
    writeln!(
        w,
        "                       <target>: registry-scoped, or tenant-scoped in one tenant /"
    )?;
    writeln!(
        w,
        "                       every active tenant. --all-tenants prints the plan; --yes runs it."
    )?;
    writeln!(w)?;
    writeln!(w, "ROLES & PERMISSIONS:")?;
    writeln!(w, "  create-role <slug> <name> [--description <s>]")?;
    writeln!(w, "                       Create a named role on a tenant.")?;
    writeln!(
        w,
        "  list-roles  <slug>   List roles and permission counts."
    )?;
    writeln!(w, "  assign-role <slug> <username> <role>")?;
    writeln!(w, "                       Add a user to a role.")?;
    writeln!(w, "  revoke-role <slug> <username> <role>")?;
    writeln!(w, "                       Remove a user from a role.")?;
    writeln!(w, "  grant-perm  <slug> <name> <codename> [--role]")?;
    writeln!(
        w,
        "                       Grant a codename to a user (default) or role (--role)."
    )?;
    writeln!(w, "  revoke-perm <slug> <name> <codename> [--role]")?;
    writeln!(
        w,
        "                       Revoke a codename from a user or role."
    )?;
    writeln!(
        w,
        "  create-api-key <slug> <username> [--label <s>] [--expires-days <N>]"
    )?;
    writeln!(
        w,
        "                       Issue a Bearer API key for a tenant user."
    )?;
    // MCP agent/skill verbs only exist when the `mcp` feature is compiled in.
    #[cfg(feature = "mcp")]
    {
        writeln!(w, "  create-agent <slug> <name>")?;
        writeln!(
            w,
            "                       Provision an MCP agent (prints its secret once)."
        )?;
        writeln!(w, "  rotate-agent-secret <slug> <name>")?;
        writeln!(
            w,
            "                       Issue a fresh secret for an MCP agent."
        )?;
        writeln!(w, "  list-agents <slug>   List a tenant's MCP agents.")?;
        writeln!(
            w,
            "  create-skill <slug> <codename> [--name ..] [--tools a,b] [--instructions ..]"
        )?;
        writeln!(
            w,
            "                       Define an MCP skill (a bundle of tools)."
        )?;
        writeln!(w, "  grant-skill <slug> <agent> <skill>")?;
        writeln!(w, "                       Grant a skill to an agent.")?;
        writeln!(w, "  revoke-skill <slug> <agent> <skill>")?;
        writeln!(w, "                       Revoke a skill from an agent.")?;
        writeln!(w, "  list-skills <slug>   List a tenant's MCP skills.")?;
        // Flags, not a positional `[label]` — the parser rejects a third
        // positional with "unexpected argument" (#1407).
        writeln!(
            w,
            "  create-user-key <slug> <username> [--label <l>] [--skill <codename>]…"
        )?;
        writeln!(
            w,
            "                       Issue a personal, user-owned MCP key (prints its token once)."
        )?;
        writeln!(w, "  list-user-keys <slug> <username>")?;
        writeln!(w, "                       List a user's personal MCP keys.")?;
        writeln!(w, "  revoke-user-key <slug> <username> <key_id>")?;
        writeln!(
            w,
            "                       Revoke one of a user's personal keys by id."
        )?;
        writeln!(w, "  map-skill-permission <slug> <skill> <permission>")?;
        writeln!(
            w,
            "                       Grant a skill to any user holding <permission> (user keys)."
        )?;
        writeln!(w, "  unmap-skill-permission <slug> <skill> <permission>")?;
        writeln!(
            w,
            "                       Remove a skill↔permission mapping."
        )?;
    }
    writeln!(w, "  seed-permissions [--slug <s>]")?;
    writeln!(
        w,
        "                       Re-seed `rustango_permissions` for one (--slug)"
    )?;
    writeln!(
        w,
        "                       or every active tenant. Idempotent — safe to"
    )?;
    writeln!(
        w,
        "                       run after adding `#[rustango(permissions)]` to"
    )?;
    writeln!(
        w,
        "                       a model without a fresh migrate cycle."
    )?;
    writeln!(w)?;
    writeln!(w, "AUDIT:")?;
    writeln!(
        w,
        "  audit-cleanup --days <N>     Delete entries older than N days (registry + all active tenants)."
    )?;
    writeln!(
        w,
        "  audit-cleanup --keep-last <N> Keep N most recent entries per row."
    )?;
    writeln!(
        w,
        "                [--tenant <s>]  Scope to one tenant instead of all."
    )?;
    writeln!(w)?;
    writeln!(w, "DATA:")?;
    writeln!(
        w,
        "  flush --tenant <s> [--yes]   Wipe one tenant's tables; the registry is never flushed."
    )?;
    writeln!(
        w,
        "  dumpdata | loaddata [--tenant <s>]  One tenant's models, or the registry's without it."
    )?;
    writeln!(w)?;
    writeln!(w, "SERVER:")?;
    writeln!(w, "  run-server [--bind <addr>]")?;
    writeln!(
        w,
        "                       Boot the HTTP server with admin + operator console."
    )?;
    writeln!(w)?;
    writeln!(w, "SCAFFOLDING:")?;
    writeln!(
        w,
        "  startapp <name> [--into <dir>] [--with-manage-bin] [--with-bootstrap-migration]"
    )?;
    writeln!(w, "                       Scaffold an app module.")?;
    writeln!(w)?;
    writeln!(w, "EXAMPLES:")?;
    writeln!(w, "  cargo run -- migrate")?;
    writeln!(
        w,
        "  cargo run -- create-operator admin   # prompts twice; RUSTANGO_PASSWORD off a TTY"
    )?;
    writeln!(
        w,
        "  cargo run -- create-tenant acme --display-name 'ACME Corp'"
    )?;
    writeln!(
        w,
        "  cargo run -- create-user acme alice --password-stdin --superuser"
    )?;
    writeln!(w, "  cargo run -- list-tenants")?;
    writeln!(w, "  cargo run -- audit-cleanup --days 90")?;
    writeln!(
        w,
        "  cargo run -- audit-cleanup --keep-last 50 --tenant acme"
    )?;
    writeln!(w)?;
    writeln!(
        w,
        "Run any verb with --help for verb-specific flags + details."
    )?;
    Ok(())
}

/// `check --deploy` findings only a tenancy deploy has.
async fn tenancy_deploy_findings<DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    facts: CliFacts,
) -> rustango::migrate::manage::DeployAuditFindings
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    #[cfg(feature = "sso")]
    let mut out = sso_check::findings(pools).await;
    #[cfg(not(feature = "sso"))]
    let mut out = {
        let _ = pools;
        rustango::migrate::manage::DeployAuditFindings::default()
    };
    tenant_scheme_audit(
        crate::tenancy::server::tenant_scheme_setting().as_deref(),
        &mut out,
    );
    if facts.provisioning {
        secret_key_audit(crate::aead::key_status(), &mut out);
    }
    role_schema_audit(&pools.registry_pool(), &mut out).await;
    out
}

/// A tenant schema named like a role leads that role's default
/// `search_path`; new ones are refused, existing ones are only named.
async fn role_schema_audit(
    registry: &crate::sql::Pool,
    out: &mut rustango::migrate::manage::DeployAuditFindings,
) {
    #[cfg(feature = "postgres")]
    #[allow(irrefutable_let_patterns)]
    if let crate::sql::Pool::Postgres(pg) = registry {
        use crate::core::Column as _;
        use crate::sql::FetcherPool as _;
        let orgs: Vec<crate::tenancy::Org> = match crate::tenancy::Org::objects()
            .where_(
                crate::tenancy::Org::storage_mode
                    .eq(crate::tenancy::StorageMode::Schema.as_str().to_owned()),
            )
            .fetch(registry)
            .await
        {
            Ok(orgs) => orgs,
            Err(e) => {
                out.warnings
                    .push(format!("could not list schema-mode tenants: {e}"));
                return;
            }
        };
        for org in orgs {
            let schema = org.effective_schema();
            if crate::tenancy::provision::is_role_name(pg, schema)
                .await
                .unwrap_or(false)
            {
                out.warnings.push(format!(
                    "tenant `{}` lives in schema `{schema}`, the name of a database role: that \
                     role's sessions see this tenant's tables before `public`; move it to another \
                     schema (a database move and back) or rename the role",
                    org.slug
                ));
            }
        }
    }
    #[cfg(not(feature = "postgres"))]
    let _ = (registry, out);
}

/// Provisioning seals server passwords and tenant URLs with this key.
fn secret_key_audit(
    status: crate::aead::KeyStatus,
    out: &mut rustango::migrate::manage::DeployAuditFindings,
) {
    use crate::aead::KeyStatus;
    match status {
        KeyStatus::Missing => out.warnings.push(
            "RUSTANGO_SECRET_KEY is unset — tenant provisioning is mounted but cannot save \
             server passwords, and new tenant URLs are stored unsealed; set 32+ random bytes \
             (`openssl rand -base64 48`) and back it up"
                .into(),
        ),
        KeyStatus::Short => out.warnings.push(
            "RUSTANGO_SECRET_KEY is shorter than 32 bytes — sealed secrets use a weak key".into(),
        ),
        KeyStatus::DevFile => out.warnings.push(
            "RUSTANGO_SECRET_KEY is unset — sealed secrets use the dev key file \
             `var/.rustango_secret.key`, which a redeploy loses; set the env var \
             (`openssl rand -base64 48`) and back it up"
                .into(),
        ),
        KeyStatus::Ok => out
            .info
            .push("RUSTANGO_SECRET_KEY is set for sealed secrets".into()),
    }
}

/// The impersonation handoff carries a one-time superuser login (#2425).
fn tenant_scheme_audit(
    setting: Option<&str>,
    out: &mut rustango::migrate::manage::DeployAuditFindings,
) {
    match setting {
        Some("https") => {}
        Some(other) => out.warnings.push(format!(
            "RUSTANGO_TENANT_SCHEME is `{other}` — impersonation handoff tokens go out in \
             clear; set it to `https`"
        )),
        None => out.warnings.push(
            "RUSTANGO_TENANT_SCHEME is unset — impersonation links use https only while \
             cookies are Secure; set it to `https`"
                .into(),
        ),
    }
}

#[cfg(test)]
mod deploy_tests {
    use super::*;

    /// A missing or short secret key is flagged when provisioning is mounted.
    #[test]
    fn a_missing_or_short_secret_key_is_flagged() {
        use crate::aead::KeyStatus;
        for (status, flagged) in [
            (KeyStatus::Missing, true),
            (KeyStatus::Short, true),
            (KeyStatus::DevFile, true),
            (KeyStatus::Ok, false),
        ] {
            let mut out = rustango::migrate::manage::DeployAuditFindings::default();
            secret_key_audit(status, &mut out);
            assert_eq!(
                out.warnings
                    .iter()
                    .any(|w| w.contains("RUSTANGO_SECRET_KEY")),
                flagged,
                "{status:?}"
            );
        }
    }

    /// #2425 — an unset or non-https tenant scheme is flagged; https is not.
    #[test]
    fn a_tenant_scheme_that_is_not_https_is_flagged() {
        for (setting, flagged) in [(None, true), (Some("http"), true), (Some("https"), false)] {
            let mut out = rustango::migrate::manage::DeployAuditFindings::default();
            tenant_scheme_audit(setting, &mut out);
            assert_eq!(
                out.warnings
                    .iter()
                    .any(|w| w.contains("RUSTANGO_TENANT_SCHEME")),
                flagged,
                "{setting:?}"
            );
        }
    }
}