rustango 0.30.19

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
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
//! Admin URL routing — Django's `urls.py` shape.
//!
//! `router(pool)` and `Builder` build the axum [`Router`] that maps each
//! HTTP path to a handler in [`super::views`]. Mounted via
//! `Router::new().nest("/admin", admin::router(pool))`.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::core::SqlValue;
use crate::sql::sqlx::PgPool;
use axum::routing::{get, post};
use axum::Router;

use super::errors::AdminError;
use super::views;

/// Future returned by an [`AdminAction`] handler.
pub type AdminActionFuture<'a> = Pin<Box<dyn Future<Output = Result<(), AdminError>> + Send + 'a>>;

/// Bulk action handler. Receives the model's `&PgPool` (not a tenant
/// connection — the admin runs with the connection the request lives
/// on, so search_path is already correct) and the parsed PK list of
/// the rows the operator selected. Return `Ok(())` on success;
/// `AdminError::Internal(...)` for failure (renders as 500). Built-in
/// `delete_selected` uses this signature.
pub type AdminActionFn =
    Arc<dyn for<'a> Fn(&'a PgPool, &'a [SqlValue]) -> AdminActionFuture<'a> + Send + Sync>;

/// Per-table action registry: model `table` name → action name →
/// handler. The action name must also appear in the model's
/// `admin(actions = "...")` allowlist; the registry just maps the
/// allowlisted names to their callables.
pub(crate) type AdminActionRegistry = HashMap<&'static str, HashMap<&'static str, AdminActionFn>>;

/// Mount the admin under any prefix using axum's nesting:
/// `Router::new().nest("/admin", crate::admin::router(pool))`.
///
/// Equivalent to `Builder::new(pool).build()`. For finer control (model
/// allowlist, read-only tables) use [`Builder`].
pub fn router(pool: PgPool) -> Router {
    Builder::new(pool).build()
}

/// Configurable admin builder.
///
/// ```ignore
/// let app = admin::Builder::new(pool)
///     .show_only(["user", "post", "audit_log"])
///     .read_only(["audit_log"])
///     .build();
/// ```
#[must_use]
pub struct Builder {
    pool: PgPool,
    config: Config,
}

#[derive(Clone, Default)]
pub(crate) struct Config {
    /// Display name shown in the sidebar header. `None` → "Rustango Admin".
    pub(crate) title: Option<String>,
    /// Optional subtitle shown below the title in the sidebar.
    pub(crate) subtitle: Option<String>,
    /// Per-tenant brand name override. Falls back to `title` when
    /// `None`. Set per-request by the tenancy admin from `Org.brand_name`.
    pub(crate) brand_name: Option<String>,
    /// Per-tenant brand tagline. Falls back to `subtitle` when `None`.
    pub(crate) brand_tagline: Option<String>,
    /// Public URL of the tenant logo (e.g. `/__brand__/{slug}/logo.png`).
    pub(crate) brand_logo_url: Option<String>,
    /// Theme mode — `"light"`, `"dark"`, `"auto"`. `None` → `"auto"`.
    pub(crate) theme_mode: Option<String>,
    /// Pre-built CSS variable assignments derived from the tenant's
    /// `primary_color`. Inlined verbatim into `<style>:root{ ... }`;
    /// the tenancy admin builds it via [`branding::build_brand_css`]
    /// which guarantees the body is safelisted.
    pub(crate) tenant_brand_css: Option<String>,
    /// Tables visible in the admin. `None` = every registered model.
    pub(crate) allowed_tables: Option<HashSet<String>>,
    /// Tables whose mutating routes are blocked and whose write-buttons
    /// are hidden in HTML.
    pub(crate) read_only_tables: HashSet<String>,
    /// Global read-only mode — when true, **every** visible table is
    /// treated as read-only regardless of `read_only_tables`. Used by
    /// `rustango-tenancy` to gate non-superuser tenant users without
    /// having to enumerate every table at request time.
    pub(crate) read_only_all: bool,
    /// User-registered bulk action handlers (slice 11.0). Keyed by
    /// `<table_name>` then `<action_name>`. The built-in
    /// `delete_selected` is hard-coded in the handler so users don't
    /// need to register it. An action name listed in a model's
    /// `admin(actions = "...")` but NOT in this map AND not the built-in
    /// produces a 500 — same defense as the v0.10.6 unknown-action gate.
    pub(crate) actions: AdminActionRegistry,
    /// Pre-fetched permission codenames for the current user.
    /// `None` = superuser (all operations allowed).
    /// `Some(set)` = the effective codename set; `is_visible`,
    /// `is_read_only`, `can_add`, and `can_delete` consult it.
    pub(crate) user_perms: Option<HashSet<String>>,
    /// v0.27.7 — when true, the admin filters out registry-scoped
    /// models (`#[rustango(scope = "registry")]`, e.g. Org /
    /// Operator) from the sidebar + index. Tenant admins live in
    /// the per-tenant pool and can't show cross-tenant data
    /// without leaking; the registry-only models belong to the
    /// operator console. Set automatically by
    /// `TenantAdminBuilder::build()`. Standalone single-tenant
    /// admins (no tenancy) leave this false and see every model
    /// regardless of scope.
    pub(crate) tenant_mode: bool,
    /// v0.27.8 (#78) — `Some(operator_id)` when the current
    /// session is an operator-impersonation cookie. Drives the
    /// "you are impersonating" banner in admin layouts and
    /// tags audit-log entries. `None` for regular tenant-user
    /// logins.
    pub(crate) impersonated_by: Option<i64>,
    /// v0.27.9 (#59) — URL prefix the admin Router is mounted
    /// under. Threaded into every template as `{{ admin_prefix }}`
    /// so hrefs / form actions resolve correctly under any
    /// mount path. Defaults to `/__admin` (the convention every
    /// rustango-tenancy deployment uses); users mounting via
    /// `nest("/admin", admin::router(pool))` override via
    /// `Builder::admin_prefix("/admin")`. Empty string means
    /// "the admin router is the root" — supported but uncommon.
    pub(crate) admin_prefix: String,
    /// v0.28.2 (#77) — URL of the self-serve change-password
    /// page. Rendered as a sidebar link when set so users can
    /// find it. The tenant admin Builder pulls this from
    /// `RouteConfig::change_password_url`. Standalone admins
    /// leave it `None` (no auth surface to wire it to).
    pub(crate) change_password_url: Option<String>,
    /// URL suffix the audit-log view is mounted under (sibling
    /// to `admin_prefix`). The cross-row activity feed renders
    /// at `<admin_prefix><audit_url>` and the cleanup form at
    /// `<admin_prefix><audit_url>/cleanup`. Threaded into every
    /// template as `{{ audit_url }}` so the sidebar / audit-log
    /// pager / detail-page "View full history" links resolve
    /// correctly under any configuration. Default: `/__audit`
    /// (matches the v0.28 hardcoded path); the tenancy admin
    /// Builder pulls this from `RouteConfig::audit_url` —
    /// which since v0.29 (#85) defaults to `/audit` (no
    /// underscores) for friendly-URL projects.
    pub(crate) audit_url: String,
    /// v0.30.19 — URL prefix at which the framework serves
    /// embedded static assets (`rustango.png` logo, `icon.png`
    /// favicon). Threaded into chrome context as `{{ static_url }}`
    /// so admin templates can build absolute URLs (e.g. the
    /// favicon `<link rel="icon" href="{{ static_url }}/icon.png">`).
    /// Defaults to `/__static__`; tenancy admin Builder pulls this
    /// from `RouteConfig::static_url` — `/_static` under
    /// friendly RouteConfig, `/__static__` under default.
    pub(crate) static_url: String,
    /// v0.30.9 — tables for which the admin list view skips the
    /// `SELECT COUNT(*)` round-trip and renders a "Page N" pager
    /// (driven by has-next-page detection on the row count) instead
    /// of "Page N of M". Required for tables in the millions of
    /// rows where COUNT(*) takes seconds even with indexes.
    /// Per-request override: `?count=skip` (or `?count=0`) on the
    /// list URL applies the same skip without a code change.
    pub(crate) skip_count_tables: HashSet<String>,
}

impl Builder {
    pub fn new(pool: PgPool) -> Self {
        let mut config = Config::default();
        // v0.27.9 (#59) — default admin mount prefix matches the
        // convention every rustango-tenancy deployment uses.
        // Users who mount under a different path (e.g.
        // `nest("/admin", admin::router(pool))`) override via
        // `Builder::admin_prefix(...)`.
        config.admin_prefix = "/__admin".to_owned();
        // Default audit suffix matches v0.28 hardcoded path so
        // standalone admins (no RouteConfig) keep their existing
        // bookmarks. Tenancy admins override via
        // `Builder::audit_url(...)` from `RouteConfig::audit_url`.
        config.audit_url = "/__audit".to_owned();
        // v0.30.19 — default static_url matches the framework's
        // legacy hardcoded path. Tenancy admin overrides via
        // `Builder::static_url(...)` from `RouteConfig::static_url`
        // — `/_static` under friendly, `/__static__` under default.
        config.static_url = "/__static__".to_owned();
        Self { pool, config }
    }

    /// URL prefix the admin Router is mounted under (#59,
    /// v0.27.9). Threaded into every template as
    /// `{{ admin_prefix }}` so hrefs / form actions resolve
    /// correctly under any mount path. Default: `/__admin`.
    /// Pass an empty string when the admin is the root router.
    /// Trailing slash is stripped.
    #[must_use]
    pub fn admin_prefix(mut self, prefix: impl Into<String>) -> Self {
        let s: String = prefix.into();
        let trimmed = s.trim_end_matches('/').to_owned();
        self.config.admin_prefix = trimmed;
        self
    }

    /// URL suffix the audit-log view is mounted at (sibling to
    /// `admin_prefix`). Trailing slash is stripped. Default:
    /// `/__audit`. Tenant admins set this from
    /// [`crate::tenancy::RouteConfig::audit_url`] (which since
    /// v0.29 #85 defaults to `/audit` — no underscores —
    /// for friendly-URL projects).
    #[must_use]
    pub fn audit_url(mut self, url: impl Into<String>) -> Self {
        let s: String = url.into();
        let trimmed = s.trim_end_matches('/').to_owned();
        self.config.audit_url = trimmed;
        self
    }

    /// URL prefix at which the framework serves embedded static
    /// assets (logo + favicon). v0.30.19. Threaded into chrome
    /// context so admin templates resolve the favicon `<link>`
    /// to the actual route. Tenancy admin Builder pulls this
    /// from [`crate::tenancy::RouteConfig::static_url`] —
    /// `/_static` under friendly, `/__static__` under default.
    #[must_use]
    pub fn static_url(mut self, url: impl Into<String>) -> Self {
        let s: String = url.into();
        let trimmed = s.trim_end_matches('/').to_owned();
        self.config.static_url = trimmed;
        self
    }

    /// URL of the self-serve change-password page (#77,
    /// v0.28.2). When set, the admin sidebar renders a
    /// "Change password" link pointing at this URL. The tenant
    /// admin Builder pulls this from
    /// [`crate::tenancy::RouteConfig::change_password_url`].
    #[must_use]
    pub fn change_password_url(mut self, url: impl Into<String>) -> Self {
        self.config.change_password_url = Some(url.into());
        self
    }

    /// Restrict the admin to these tables. Models not in the list are
    /// hidden from the index and return 404 on direct hits.
    pub fn show_only<I, S>(mut self, tables: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.config.allowed_tables = Some(tables.into_iter().map(Into::into).collect());
        self
    }

    /// Mark these tables read-only. List/detail still render; create,
    /// edit, and delete routes return 403, and the corresponding buttons
    /// are hidden in the HTML.
    pub fn read_only<I, S>(mut self, tables: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.config
            .read_only_tables
            .extend(tables.into_iter().map(Into::into));
        self
    }

    /// Mark **every** table read-only — the admin renders list/detail
    /// views but every mutating route returns 403 and write-buttons
    /// are hidden. Used by callers (e.g. `rustango-tenancy` for
    /// non-superuser tenant users) that gate by a runtime flag and
    /// don't want to enumerate every table per request.
    pub fn read_only_all(mut self) -> Self {
        self.config.read_only_all = true;
        self
    }

    /// Skip the admin list view's `SELECT COUNT(*)` round-trip for
    /// these tables. The pager renders "Page N" (with prev/next
    /// driven by has-next-page detection on the row count) instead
    /// of "Page N of M". Required for tables in the millions of
    /// rows where `COUNT(*)` with WHERE filters takes seconds.
    ///
    /// Per-request escape hatch: any list URL accepts
    /// `?count=skip` (or `?count=0`) to apply the same skip without
    /// a code change — useful for ad-hoc operator queries on big
    /// tables that aren't pre-tagged.
    ///
    /// ```ignore
    /// admin::Builder::new(pool)
    ///     .skip_count_for(["audit_log", "events"])
    ///     .build()
    /// ```
    pub fn skip_count_for<I, S>(mut self, tables: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.config
            .skip_count_tables
            .extend(tables.into_iter().map(Into::into));
        self
    }

    /// Mark the current session as an operator impersonation
    /// (v0.27.8 #78). Threads `operator_id` into `chrome_context`
    /// so the admin layout renders an unmissable banner +
    /// "End impersonation" button. Wired by
    /// `TenantAdminBuilder::build()` from the validated session
    /// cookie.
    #[must_use]
    pub fn impersonated_by(mut self, operator_id: i64) -> Self {
        self.config.impersonated_by = Some(operator_id);
        self
    }

    /// Tenant-mode filter (v0.27.7): hides registry-scoped models
    /// (`#[rustango(scope = "registry")]`) from the admin sidebar
    /// and index. Wired automatically by
    /// `TenantAdminBuilder::build()`; standalone admins leave it
    /// false. Pre-fix, registry-only models like `Org` / `Operator`
    /// surfaced inside the tenant admin even though they don't
    /// live in the tenant's storage — clicking through could leak
    /// cross-tenant data via search_path on schema-mode tenants
    /// (the registry's `public.rustango_orgs` would resolve).
    #[must_use]
    pub fn tenant_mode(mut self) -> Self {
        self.config.tenant_mode = true;
        self
    }

    /// Set the admin title shown in the sidebar header.
    /// Defaults to `"Rustango Admin"` when not set.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.config.title = Some(title.into());
        self
    }

    /// Set the subtitle shown below the title in the sidebar (optional).
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.config.subtitle = Some(subtitle.into());
        self
    }

    /// Per-tenant brand name (overrides [`Self::title`] for the
    /// sidebar header). Wired by the tenancy admin from
    /// `Org.brand_name` per request.
    #[must_use]
    pub fn brand_name(mut self, name: impl Into<String>) -> Self {
        self.config.brand_name = Some(name.into());
        self
    }

    /// Per-tenant brand tagline. Same fallback semantics as
    /// [`Self::brand_name`] — overrides [`Self::subtitle`] when set.
    #[must_use]
    pub fn brand_tagline(mut self, tagline: impl Into<String>) -> Self {
        self.config.brand_tagline = Some(tagline.into());
        self
    }

    /// Public URL of the tenant logo. Rendered as an `<img>` above
    /// the brand name in the sidebar when present.
    #[must_use]
    pub fn brand_logo_url(mut self, url: impl Into<String>) -> Self {
        self.config.brand_logo_url = Some(url.into());
        self
    }

    /// Theme mode — `"light"`, `"dark"`, or `"auto"`. Sets the
    /// `data-theme` attribute on the rendered `<html>` element.
    #[must_use]
    pub fn theme_mode(mut self, mode: impl Into<String>) -> Self {
        self.config.theme_mode = Some(mode.into());
        self
    }

    /// Pre-built per-tenant CSS variable override block. Inlined
    /// inside `<style>:root{ ... }`. Build it via
    /// `crate::tenancy::branding::build_brand_css(&org)`.
    #[must_use]
    pub fn tenant_brand_css(mut self, css: impl Into<String>) -> Self {
        self.config.tenant_brand_css = Some(css.into());
        self
    }

    /// Restrict visible and writable tables to the authenticated user's
    /// effective permission set. Pass the codenames returned by
    /// `rustango::tenancy::permissions::user_permissions(uid, pool)`.
    ///
    /// * Tables where the user lacks `{table}.view` are hidden from the
    ///   index and return 404 on direct hits.
    /// * Tables where the user lacks `{table}.change` are rendered
    ///   read-only (edit form still renders; save returns 403).
    /// * `{table}.add` gates the create form and create submit.
    /// * `{table}.delete` gates delete submit and `delete_selected`.
    ///
    /// Superusers should NOT call this method — omitting it means `None`
    /// which bypasses all permission checks and allows everything.
    pub fn with_user_perms<I: IntoIterator<Item = String>>(mut self, perms: I) -> Self {
        self.config.user_perms = Some(perms.into_iter().collect());
        self
    }

    /// Register a user-defined bulk action handler.
    ///
    /// `model_table` must match the target Model's `table = "..."`
    /// attribute. `action_name` must also appear in that model's
    /// `admin(actions = "...")` allowlist; the attribute is the
    /// allowlist, this is the executable.
    ///
    /// The handler receives the pool and the parsed PK list of the
    /// selected rows. Use it to implement publish, archive, recompute,
    /// etc. — anything that runs over a batch of rows.
    ///
    /// ```ignore
    /// use rustango::sql::sqlx::PgPool;
    /// use rustango::core::SqlValue;
    /// use rustango::admin::AdminError;
    /// async fn mark_published(pool: &PgPool, pks: &[SqlValue]) -> Result<(), AdminError> {
    ///     // ... custom UPDATE here ...
    ///     Ok(())
    /// }
    /// admin::Builder::new(pool)
    ///     .register_action("post", "mark_published", |pool, pks| {
    ///         Box::pin(mark_published(pool, pks))
    ///     })
    ///     .build();
    /// ```
    pub fn register_action<F>(
        mut self,
        model_table: &'static str,
        action_name: &'static str,
        handler: F,
    ) -> Self
    where
        F: for<'a> Fn(&'a PgPool, &'a [SqlValue]) -> AdminActionFuture<'a> + Send + Sync + 'static,
    {
        self.config
            .actions
            .entry(model_table)
            .or_default()
            .insert(action_name, Arc::new(handler));
        self
    }

    pub fn build(self) -> Router {
        let audit_path = self.config.audit_url.clone();
        let audit_cleanup_path = format!("{audit_path}/cleanup");
        Router::new()
            .route("/", get(views::index))
            .route(&audit_path, get(super::audit::audit_log_view))
            .route(
                &audit_cleanup_path,
                post(super::audit::audit_cleanup_submit),
            )
            .route(
                "/{table}",
                get(views::table_view).post(views::create_submit),
            )
            .route("/{table}/new", get(views::create_form))
            .route("/{table}/__action", post(views::action_submit))
            .route(
                "/{table}/{pk}",
                get(views::detail_view).post(views::update_submit),
            )
            .route("/{table}/{pk}/edit", get(views::edit_form))
            .route("/{table}/{pk}/delete", post(views::delete_submit))
            .with_state(AppState {
                pool: self.pool,
                config: Arc::new(self.config),
            })
    }
}

/// Shared per-request state — the pool plus the resolved `Config`.
/// Cloned on every request (Arc-wrapped Config makes that cheap).
#[derive(Clone)]
pub(crate) struct AppState {
    pub(crate) pool: PgPool,
    pub(crate) config: Arc<Config>,
}

impl AppState {
    pub(crate) fn is_visible(&self, table: &str) -> bool {
        let allowlist_ok = self
            .config
            .allowed_tables
            .as_ref()
            .is_none_or(|allowed| allowed.contains(table));
        if !allowlist_ok {
            return false;
        }
        // When a per-user perm set is present, require `{table}.view`.
        if let Some(perms) = &self.config.user_perms {
            return perms.contains(&format!("{table}.view"));
        }
        true
    }

    /// v0.27.7 — scope filter. Tenant admins (`tenant_mode = true`)
    /// hide registry-only models (`#[rustango(scope = "registry")]`,
    /// e.g. `Org` / `Operator`) so cross-tenant data can't surface
    /// inside a tenant subdomain. Standalone admins return true for
    /// every scope.
    pub(crate) fn scope_visible(&self, scope: crate::core::ModelScope) -> bool {
        if !self.config.tenant_mode {
            return true;
        }
        scope == crate::core::ModelScope::Tenant
    }

    /// Returns `true` when the table's mutating routes (edit/update)
    /// should be blocked. Checks the global/per-table read-only flags
    /// first; when `user_perms` is set also checks `{table}.change`.
    pub(crate) fn is_read_only(&self, table: &str) -> bool {
        if self.config.read_only_all || self.config.read_only_tables.contains(table) {
            return true;
        }
        if let Some(perms) = &self.config.user_perms {
            return !perms.contains(&format!("{table}.change"));
        }
        false
    }

    /// `true` when this table was tagged via
    /// [`Builder::skip_count_for`] — the admin list view skips the
    /// `SELECT COUNT(*)` round-trip and renders a no-total pager.
    pub(crate) fn count_skipped_for_table(&self, table: &str) -> bool {
        self.config.skip_count_tables.contains(table)
    }

    /// `true` when the user may create rows in `table`.
    pub(crate) fn can_add(&self, table: &str) -> bool {
        if self.config.read_only_all || self.config.read_only_tables.contains(table) {
            return false;
        }
        if let Some(perms) = &self.config.user_perms {
            return perms.contains(&format!("{table}.add"));
        }
        true
    }

    /// `true` when the user may delete rows from `table`.
    pub(crate) fn can_delete(&self, table: &str) -> bool {
        if self.config.read_only_all || self.config.read_only_tables.contains(table) {
            return false;
        }
        if let Some(perms) = &self.config.user_perms {
            return perms.contains(&format!("{table}.delete"));
        }
        true
    }

    /// Look up a registered action handler. Returns `None` for the
    /// built-in `delete_selected` (which the handler short-circuits)
    /// and for action names that haven't been registered.
    pub(crate) fn action_handler(&self, table: &str, action: &str) -> Option<AdminActionFn> {
        self.config
            .actions
            .get(table)
            .and_then(|m| m.get(action))
            .cloned()
    }
}

#[cfg(test)]
mod scope_filter_tests {
    use super::*;
    use crate::core::ModelScope;
    use std::sync::Arc;

    fn state_with(tenant_mode: bool) -> AppState {
        let mut cfg = Config::default();
        cfg.tenant_mode = tenant_mode;
        AppState {
            // sqlx PgPool isn't trivially constructable in unit
            // tests; use a lazy connect to a non-existent URL —
            // none of the methods we exercise here touch the pool.
            pool: PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused")
                .expect("connect_lazy never fails"),
            config: Arc::new(cfg),
        }
    }

    #[tokio::test]
    async fn standalone_admin_sees_every_scope() {
        // v0.27.7 regression guard: single-tenant projects must
        // continue to see registry-scoped models in their admin.
        let state = state_with(false);
        assert!(state.scope_visible(ModelScope::Tenant));
        assert!(state.scope_visible(ModelScope::Registry));
    }

    #[tokio::test]
    async fn tenant_admin_hides_registry_scoped_models() {
        // v0.27.7 fix: tenant admins must NOT surface
        // `#[rustango(scope = "registry")]` models (Org / Operator
        // etc.) — those don't live in the tenant pool and clicking
        // them on a schema-mode tenant would leak cross-tenant
        // data via search_path.
        let state = state_with(true);
        assert!(state.scope_visible(ModelScope::Tenant));
        assert!(!state.scope_visible(ModelScope::Registry));
    }

    #[tokio::test]
    async fn tenant_mode_setter_flips_flag() {
        let pool = PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused")
            .expect("connect_lazy never fails");
        let builder = Builder::new(pool).tenant_mode();
        assert!(builder.config.tenant_mode);
    }

    // v0.27.9 (#59) — admin_prefix template variable regression
    // guard. Default must be `/__admin` (the convention used by
    // every rustango-tenancy deployment); setter must trim trailing
    // slashes; empty string must be supported for "admin is the
    // root router" mounts.

    #[tokio::test]
    async fn admin_prefix_defaults_to_admin_underscore() {
        let pool = PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap();
        let builder = Builder::new(pool);
        assert_eq!(builder.config.admin_prefix, "/__admin");
    }

    /// `Builder::skip_count_for` accumulates table names; the
    /// `count_skipped_for_table` checker returns true exactly for
    /// the tagged tables. Untagged tables stay on the COUNT path.
    #[tokio::test]
    async fn skip_count_for_marks_tables_and_checker_reads_them() {
        let pool = PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap();
        let b = Builder::new(pool).skip_count_for(["audit_log", "events"]);
        let state = AppState {
            pool: PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap(),
            config: Arc::new(b.config),
        };
        assert!(state.count_skipped_for_table("audit_log"));
        assert!(state.count_skipped_for_table("events"));
        assert!(!state.count_skipped_for_table("post"));
        assert!(!state.count_skipped_for_table(""));
    }

    /// Multiple `.skip_count_for(...)` calls union the table sets
    /// rather than replacing — same shape as `read_only` does.
    #[tokio::test]
    async fn skip_count_for_unions_across_calls() {
        let pool = PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap();
        let b = Builder::new(pool)
            .skip_count_for(["audit_log"])
            .skip_count_for(["events"]);
        let state = AppState {
            pool: PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap(),
            config: Arc::new(b.config),
        };
        assert!(state.count_skipped_for_table("audit_log"));
        assert!(state.count_skipped_for_table("events"));
    }

    #[tokio::test]
    async fn admin_prefix_setter_strips_trailing_slash() {
        let pool = PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap();
        let b = Builder::new(pool).admin_prefix("/admin/");
        assert_eq!(b.config.admin_prefix, "/admin");
    }

    #[tokio::test]
    async fn admin_prefix_supports_empty_for_root_mount() {
        let pool = PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused").unwrap();
        let b = Builder::new(pool).admin_prefix("");
        assert_eq!(b.config.admin_prefix, "");
    }
}