Skip to main content

rustango_cms/
seed.rs

1//! Per-tenant `cms_page_type` seeding.
2//!
3//! At boot time the framework hooks `Cli::seed(rcms::ensure_seeded)`,
4//! which fans out across every active `Org` and upserts one row per
5//! `PageTypeHandler` registered via [`crate::register_page_type!`]
6//! (or by hand via [`crate::PageTypeHandlerRegistration`]).
7//!
8//! Idempotent — re-running on an already-seeded tenant overwrites
9//! the metadata fields (verbose_name, default_template,
10//! allowed_parent_types) but never touches the surrogate `id`, so
11//! existing FKs from `cms_page.page_type_id` remain valid.
12
13use rustango::core::Column as _;
14use rustango::sql::{sqlx, Auto, ExecError, FetcherPool as _};
15use rustango::tenancy::{Org, TenantPools};
16
17use crate::page_type::{registered_handlers, PageTypeHandler};
18use crate::page_type_model::PageType;
19
20/// Errors from `ensure_seeded`. Propagates the underlying tenancy /
21/// driver errors verbatim so callers can match on them.
22#[derive(Debug, thiserror::Error)]
23pub enum SeedError {
24    #[error(transparent)]
25    Tenancy(#[from] rustango::tenancy::TenancyError),
26    #[error(transparent)]
27    Db(#[from] ExecError),
28    #[error(transparent)]
29    Sqlx(#[from] sqlx::Error),
30
31    /// A seeder's own failure: bad configuration, a missing
32    /// registration, seed data it cannot read. Without this a host
33    /// seeder can only report driver errors, so anything that is
34    /// genuinely wrong with *its* inputs has to be forced into a
35    /// database error that misdescribes it.
36    #[error("{0}")]
37    Seeder(String),
38}
39
40/// Walk every active `Org` and ensure the tenant has one
41/// `cms_page_type` row per registered `PageTypeHandler`.
42///
43/// Wire as the `Cli::seed` hook so it runs once per boot after
44/// migrations. Cheap — does one SELECT + zero-or-one
45/// INSERT/UPDATE per (tenant, handler) pair.
46///
47/// Accepts a tri-dialect [`rustango::sql::Pool`] so the same hook
48/// works across Postgres / SQLite / MySQL registries. Internally it
49/// matches the active variant and builds a `TenantPools<DB>` parameterized
50/// by the concrete sqlx backend — the seeding loop itself is fully
51/// dialect-agnostic because [`TenantPools::scoped_pool_dyn`] and
52/// `upsert_page_type` both speak the erased [`rustango::sql::Pool`].
53///
54/// Pre-conditions:
55/// - The registry DB is reachable via `registry`.
56/// - Tenants' tenant-scope migrations (including `0001_initial`
57///   from this crate) have already been applied so `cms_page_type`
58///   exists.
59///
60/// # Errors
61/// Driver / tenancy errors from any tenant; the first failure
62/// short-circuits the whole fan-out.
63pub async fn ensure_seeded(registry: &rustango::sql::Pool) -> Result<(), SeedError> {
64    // Queued jobs resolve tenants they weren't dispatched with through it.
65    crate::task_queue::set_registry(registry.clone());
66    match registry {
67        #[cfg(feature = "postgres")]
68        rustango::sql::Pool::Postgres(pg) => {
69            seed_orgs(TenantPools::<sqlx::Postgres>::new(pg.clone())).await
70        }
71        #[cfg(feature = "sqlite")]
72        rustango::sql::Pool::Sqlite(sq) => {
73            seed_orgs(TenantPools::<sqlx::Sqlite>::new(sq.clone())).await
74        }
75        #[cfg(feature = "mysql")]
76        rustango::sql::Pool::Mysql(my) => {
77            seed_orgs(TenantPools::<sqlx::MySql>::new(my.clone())).await
78        }
79    }
80}
81
82async fn seed_orgs<DB>(pools: TenantPools<DB>) -> Result<(), SeedError>
83where
84    DB: sqlx::Database,
85    rustango::sql::Pool: From<sqlx::Pool<DB>>,
86{
87    let registry_pool = pools.registry_pool();
88    let orgs: Vec<Org> = Org::objects().fetch(&registry_pool).await?;
89
90    // #689 — every tenant is seeded even when one fails: a broken tenant
91    // used to leave every tenant after it unseeded until the next boot.
92    let mut first_err = None;
93    for org in orgs {
94        if !org.active {
95            continue;
96        }
97        let seeded = match pools.scoped_pool_dyn(&org).await {
98            Ok(tenant_pool) => seed_tenant(&tenant_pool, &org).await,
99            Err(e) => Err(e.into()),
100        };
101        match seeded {
102            Ok(()) => mark_seeded(&org.slug),
103            Err(e) => {
104                tracing::error!(target: "rustango_cms::seed", tenant = %org.slug, error = %e, "tenant seed failed");
105                first_err.get_or_insert(e);
106            }
107        }
108    }
109    first_err.map_or(Ok(()), Err)
110}
111
112/// Tenants seeded by this process — at boot, or lazily on first request.
113static SEEDED: std::sync::Mutex<Option<std::collections::HashSet<String>>> =
114    std::sync::Mutex::new(None);
115
116fn mark_seeded(slug: &str) {
117    let mut g = SEEDED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
118    g.get_or_insert_with(Default::default).insert(slug.to_owned());
119}
120
121fn is_seeded(slug: &str) -> bool {
122    let g = SEEDED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
123    g.as_ref().is_some_and(|set| set.contains(slug))
124}
125
126/// Seed `org` if this process hasn't yet. A tenant provisioned
127/// while the server runs — operator console, provisioning webhook,
128/// `create-tenant` — gets its tracked migrations but missed the boot-time
129/// seed, so it had no page types, roles or locale until a restart. One
130/// tenant is seeded at a time, and a second request for it waits rather
131/// than seeding again.
132///
133/// # Errors
134/// The first failing seed step; the tenant stays unmarked and the next
135/// request retries.
136pub async fn ensure_tenant_seeded(pool: &rustango::sql::Pool, org: &Org) -> Result<(), SeedError> {
137    if is_seeded(&org.slug) {
138        return Ok(());
139    }
140    static LOCK: rustango::__private_runtime::tokio::sync::Mutex<()> =
141        rustango::__private_runtime::tokio::sync::Mutex::const_new(());
142    let _held = LOCK.lock().await;
143    if is_seeded(&org.slug) {
144        return Ok(());
145    }
146    seed_tenant(pool, org).await?;
147    mark_seeded(&org.slug);
148    tracing::info!(target: "rustango_cms::seed", tenant = %org.slug, "seeded a tenant provisioned after boot");
149    Ok(())
150}
151
152/// Middleware running [`ensure_tenant_seeded`] for the request's tenant.
153/// Layered onto the admin and public routers; costs one set lookup once a
154/// tenant is seeded. A tenant that can't be resolved or seeded falls
155/// through — the handler reports that as it did before.
156pub(crate) async fn lazy_seed_layer(
157    req: axum::http::Request<axum::body::Body>,
158    next: axum::middleware::Next,
159) -> axum::response::Response {
160    use rustango::tenancy::OrgResolver as _;
161    let (mut parts, body) = req.into_parts();
162    if let Some(ctx) = parts
163        .extensions
164        .get::<std::sync::Arc<rustango::extractors::TenantContext>>()
165        .cloned()
166    {
167        if let Ok(Some(org)) = ctx.resolver.resolve(&mut parts, &ctx.pools.registry_pool()).await {
168            if !is_seeded(&org.slug) {
169                match ctx.pools.scoped_pool_dyn(&org).await {
170                    Ok(pool) => {
171                        if let Err(e) = ensure_tenant_seeded(&pool, &org).await {
172                            tracing::error!(target: "rustango_cms::seed", tenant = %org.slug, error = %e, "lazy tenant seed failed");
173                        }
174                    }
175                    Err(e) => tracing::warn!(target: "rustango_cms::seed", tenant = %org.slug, error = %e, "tenant pool unavailable for seeding"),
176                }
177            }
178        }
179    }
180    next.run(axum::http::Request::from_parts(parts, body)).await
181}
182
183/// Everything a tenant needs beyond its tracked migrations: registry rows
184/// for page, library and taxonomy types, themes, roles, the default
185/// locale, the ensure-only tables and columns, MCP skills and the host's
186/// seeders. Idempotent. Run for every tenant at boot, and for a tenant
187/// provisioned while the server runs on its first request.
188///
189/// # Errors
190/// The first failing step.
191pub async fn seed_tenant(tenant_pool: &rustango::sql::Pool, org: &Org) -> Result<(), SeedError> {
192    let tenant_pool = tenant_pool.clone();
193    for handler in registered_handlers() {
194        upsert_page_type(&tenant_pool, handler.as_ref()).await?;
195    }
196    // Seed `cms_library_type` rows for every
197    // `register_library_type!`-registered handler too.
198    for handler in crate::library::registered_handlers() {
199        crate::library::ensure_library_type_row(&tenant_pool, handler.as_ref()).await?;
200    }
201    // #557 — seed `cms_taxonomy` rows from the taxonomy handler
202    // inventory (built-in `category` + any `register_taxonomy!` ones),
203    // mirroring `upsert_page_type`. The `cms_taxonomy`/`cms_category`
204    // tables come from the migration (0005_categories), so this is a
205    // best-effort sync: on a tenant that hasn't run `migrate-tenants`
206    // yet the table is absent — warn, don't fail boot.
207    for handler in crate::category::registered_handlers() {
208        if let Err(e) = crate::category::upsert_taxonomy(&tenant_pool, handler.as_ref()).await {
209            tracing::warn!(
210                target: "rustango_cms::seed",
211                taxonomy = handler.slug(), error = %e,
212                "taxonomy upsert failed — has `migrate-tenants` created cms_taxonomy?"
213            );
214        }
215    }
216    // Theme presets — six MUI-aligned rows. Idempotent upsert
217    // keyed on `slug`; safe to re-run.
218    crate::theme_seed::ensure_themes_seeded(&tenant_pool).await?;
219    // Mirror every existing form's `notify_emails` into a notification
220    // target. Without this only forms saved *after* the notification
221    // service landed would notify anyone — the setting would still be
222    // sitting in the form, visibly configured, quietly doing nothing.
223    // Idempotent: `sync_form_email` upserts one managed target per form.
224    if let Err(e) = reconcile_form_notification_targets(&tenant_pool).await {
225        tracing::warn!(
226            target: "rustango_cms::seed",
227            error = %e,
228            "could not reconcile form notification targets"
229        );
230    }
231    // Default "Root" media collection — created once per tenant
232    // (#5) so the upload form / media list always has a place
233    // to land. Idempotent: no-op when any collection row exists.
234    ensure_root_media_collection(&tenant_pool).await?;
235    // Default Viewer / Editor / Administrator roles for the
236    // permissions matrix (#33). Idempotent: skipped per-role
237    // when a row with the same `name` already exists, so
238    // edits made by admins through the matrix survive a
239    // re-seed.
240    ensure_default_roles(&tenant_pool).await?;
241    // #452 — seed a default `en` locale so a fresh tenant satisfies
242    // the "exactly one is_default" invariant the admin enforces;
243    // without it `resolve_locale` returns None on first boot.
244    ensure_default_locale(&tenant_pool).await?;
245    // #544 FB-11 — ensure the form-submission table exists (created via
246    // CREATE TABLE IF NOT EXISTS since gen_migration is blocked).
247    crate::forms::submit::ensure_table(&tenant_pool).await?;
248    // Error pages — ensure the ErrorPage extension table exists (same
249    // CREATE TABLE IF NOT EXISTS pattern). The `cms_page_type` registry
250    // row itself comes from `upsert_page_type` via the handler inventory.
251    crate::error_pages::ensure_table(&tenant_pool).await?;
252    // #762 — UNIQUE (page_id, sequence) on revisions, so concurrent
253    // saves can't share a sequence. Warns: without it only that race
254    // stays open.
255    if let Err(e) = crate::revision::ensure_unique_sequence(&tenant_pool).await {
256        tracing::warn!(target: "rustango_cms::seed", error = %e, "revision sequence index not created");
257    }
258    // #553 — redirect engine v2 columns (overrides_live, page links,
259    // is_active/disabled_reason). ALTER-based ensure, idempotent per boot.
260    crate::redirect::ensure_columns(&tenant_pool).await?;
261    // Default analytics — ensure the event table (+ indexes) exists and
262    // prune events past the retention window. Idempotent per boot.
263    crate::analytics::ensure_table(&tenant_pool).await?;
264    let retain = crate::analytics::retention::retention_days(&tenant_pool).await;
265    if let Err(e) = crate::analytics::retention::prune(&tenant_pool, retain).await {
266        tracing::warn!(error = %e, "analytics retention prune failed");
267    }
268    // #729 — the GIN index behind Postgres full-text search. Without it
269    // every search re-parses every page (to filter and again to rank).
270    // A no-op off Postgres; a role without CREATE privilege only loses
271    // the speed-up, so it warns rather than failing the boot.
272    if let Err(e) = crate::search::ensure_pg_fts_index(&tenant_pool).await {
273        tracing::warn!(error = %e, "full-text search index not created");
274    }
275    // #532 — editable admin-translation overrides. The model is
276    // `managed = false`, so create its table here (idempotent CREATE TABLE
277    // IF NOT EXISTS); the framework admin can then browse/edit it and the
278    // shared translator picks edits up via `i18n::maybe_refresh_overrides`.
279    rustango::i18n::db::ensure_table_pool(&tenant_pool).await?;
280    // #587 — MCP skills: bundle the CMS tools and map each bundle onto the
281    // existing permission codenames, so a user-owned key's capabilities
282    // follow the tenant's RBAC exactly (see `crate::mcp`).
283    if let Err(e) = ensure_mcp_skills(&tenant_pool).await {
284        tracing::warn!(error = %e, "mcp skill seeding failed");
285    }
286    // #733 — overrides live on disk by slug, and a purged tenant's
287    // slug can be reused. Bind this tenant's directory to its database
288    // so a successor never renders through the old customer's files.
289    if let Some(templates) = crate::tenant_templates::installed() {
290        match crate::tenant_templates::database_birth(&tenant_pool).await {
291            Ok(Some(owner)) => match templates.claim(&org.slug, &owner) {
292                Ok(crate::tenant_templates::Claim::MovedAside { previous_owner, to }) => {
293                    tracing::warn!(
294                        target: "rustango_cms::seed",
295                        tenant = %org.slug, previous_owner, to = %to.display(),
296                        "template overrides belonged to an earlier tenant with this slug; moved aside"
297                    );
298                }
299                Ok(_) => {}
300                Err(e) => tracing::warn!(target: "rustango_cms::seed", tenant = %org.slug, error = %e, "could not claim template overrides"),
301            },
302            Ok(None) => {}
303            Err(e) => tracing::warn!(target: "rustango_cms::seed", tenant = %org.slug, error = %e, "could not read the database's identity"),
304        }
305    }
306    // Host-registered seeding, last: a host's own tables, roles and
307    // default rows may depend on anything above, and nothing above
308    // depends on them.
309    fire_tenant_seeders(&tenant_pool, &org).await?;
310    // #683 — after the host seeders, so their page-type tables exist:
311    // widen MySQL `TEXT` content columns to `LONGTEXT`. A failure only
312    // keeps the 64 KiB cap, so it warns rather than failing the boot.
313    match crate::mysql_text::widen_long_text(&tenant_pool).await {
314        Ok(0) => {}
315        Ok(n) => tracing::info!(target: "rustango_cms::seed", columns = n, "widened TEXT columns to LONGTEXT"),
316        Err(e) => tracing::warn!(target: "rustango_cms::seed", error = %e, "could not widen TEXT columns"),
317    }
318    // #726 — exact, case-sensitive matching on the columns the CMS
319    // resolves URLs, slugs and hosts by, as on Postgres and SQLite.
320    match crate::mysql_text::exact_identity_columns(&tenant_pool).await {
321        Ok(0) => {}
322        Ok(n) => tracing::info!(target: "rustango_cms::seed", columns = n, "gave identity columns a binary collation"),
323        Err(e) => tracing::warn!(target: "rustango_cms::seed", error = %e, "could not set binary collation on identity columns"),
324    }
325    Ok(())
326}
327
328// ---------------------------------------------------------------
329// TenantSeeder — the host's turn at per-tenant setup
330// ---------------------------------------------------------------
331
332/// Boxed future returned by a [`TenantSeeder`].
333pub type SeedFuture<'a> =
334    std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), SeedError>> + Send + 'a>>;
335
336/// A host-registered per-tenant seeding pass.
337///
338/// Everything above in this loop — page types, library types, roles,
339/// locales, MCP skills — is seeded per tenant with the *tenant's* pool.
340/// A host application had no way into that: `Cli::seed` hands it the
341/// **registry** pool, so a host wanting its own permission codename on a
342/// role, or a default row in its own table, either wrote to the wrong
343/// database or did without.
344///
345/// This is that hook. It runs once per active tenant per boot, with the
346/// tenant's pool, after the CMS's own seeding.
347///
348/// ```ignore
349/// fn seed<'a>(pool: &'a Pool, _org: &'a Org) -> SeedFuture<'a> {
350///     Box::pin(async move {
351///         rustango_cms::seed::grant_codename(pool, "Developer", "myapp.author").await?;
352///         Ok(())
353///     })
354/// }
355/// rustango_cms::register_tenant_seeder!(seed);
356/// ```
357///
358/// **Errors stop the boot.** That is deliberate: a seeder returning
359/// `Err` is saying this tenant is not correctly set up, and the failure
360/// this hook exists to prevent — a permission that silently reaches
361/// nobody — is exactly the kind that nothing downstream detects. A host
362/// that wants best-effort behaviour should log and return `Ok(())`
363/// itself, where it knows what is safe to skip.
364#[derive(Clone, Copy)]
365pub struct TenantSeeder(pub for<'a> fn(&'a rustango::sql::Pool, &'a Org) -> SeedFuture<'a>);
366
367inventory::collect!(TenantSeeder);
368
369/// Register a [`TenantSeeder`] at compile time.
370///
371/// The submission lives in a static initializer, so reference the
372/// containing module from `main` (the `blocks::link()` convention) or
373/// the linker may drop it.
374#[macro_export]
375macro_rules! register_tenant_seeder {
376    ($f:expr) => {
377        ::rustango_cms::inventory::submit! {
378            $crate::seed::TenantSeeder($f)
379        }
380    };
381}
382
383/// Run every registered [`TenantSeeder`] against one tenant.
384///
385/// # Errors
386/// The first seeder to fail short-circuits, matching how the rest of
387/// this fan-out treats a tenant it could not set up.
388async fn fire_tenant_seeders(
389    pool: &rustango::sql::Pool,
390    org: &Org,
391) -> Result<(), SeedError> {
392    for seeder in inventory::iter::<TenantSeeder>() {
393        (seeder.0)(pool, org).await?;
394    }
395    Ok(())
396}
397
398/// Grant `codename` to the role named `role_name`, if it isn't already.
399///
400/// The public face of the same backfill the CMS uses for its own
401/// codenames on upgrade. A host adding an admin section or an MCP tool
402/// needs its codename to reach a role, and reimplementing this means
403/// duplicating the role lookup and the already-present check — the two
404/// halves that make re-running it safe.
405///
406/// No-op when the role doesn't exist, so a host can grant to roles it
407/// doesn't own without checking first.
408///
409/// # Errors
410/// Driver / query failures.
411pub async fn grant_codename(
412    pool: &rustango::sql::Pool,
413    role_name: &str,
414    codename: &str,
415) -> Result<(), ExecError> {
416    backfill_codename(pool, role_name, codename).await
417}
418
419/// The built-in MCP skill set: codename, label, description,
420/// prompt instructions, tools, and the permission codenames (any-of)
421/// that entitle a user's key to the skill.
422type McpSkillSpec = (
423    &'static str,
424    &'static str,
425    &'static str,
426    &'static str,
427    &'static [&'static str],
428    &'static [&'static str],
429);
430
431const MCP_SKILLS: &[McpSkillSpec] = &[
432    (
433        "cms-read",
434        "CMS read",
435        "Browse page types, pages, media, snippets, locales, and translatable fields.",
436        "You are working inside this site's CMS. Discover structure with \
437         list_page_types before writing; read existing content before \
438         changing it.",
439        &[
440            "list_page_types",
441            "search_pages",
442            "get_page",
443            "list_locales",
444            "list_media",
445            "list_collections",
446            "list_snippets",
447            "list_translatable_fields",
448        ],
449        &["cms_page.view"],
450    ),
451    (
452        "cms-write",
453        "CMS write",
454        "Create and edit pages, upload media, put media onto a page, and \
455         manage snippets.",
456        "Create drafts unless the user explicitly asks to publish. Reuse \
457         existing media via list_media before uploading duplicates. \
458         Uploading a file only files it in the library — call attach_media \
459         to actually put it on a page, either into a chooser field or as an \
460         image block in the body (list_page_types names both).",
461        &[
462            "create_page",
463            "update_page",
464            "upload_media",
465            "attach_media",
466            "upsert_snippet",
467        ],
468        &["cms_page.edit", "cms_page.add"],
469    ),
470    (
471        "cms-publish",
472        "CMS publish",
473        "Publish pages to the live site.",
474        "Publishing makes content live immediately — confirm intent before \
475         calling publish_page.",
476        &["publish_page"],
477        &["cms_page.publish"],
478    ),
479    (
480        "cms-templates",
481        "CMS templates",
482        "Read, create and modify this site's templates, and choose which \
483         template a page type renders with.",
484        "Templates are Tera. Read the inherited body before customising a \
485         template — editing one creates a copy for this site and leaves the \
486         shared version alone. validate_template checks a body without \
487         writing it; prefer it while iterating. There is deliberately no \
488         delete tool: reverting a customisation is left to a person in the \
489         admin, so if a template should stop doing something, rewrite it.",
490        &[
491            "list_templates",
492            "read_template",
493            "write_template",
494            "validate_template",
495            "set_page_type_template",
496        ],
497        &[crate::admin::TEMPLATE_EDIT_CODENAME],
498    ),
499    (
500        "cms-translate",
501        "CMS translate",
502        "Write translation overrides for pages in any non-default locale.",
503        "Use list_translatable_fields to get the exact field paths and \
504         canonical text; translate faithfully and keep markup intact.",
505        &["upsert_translations"],
506        &["cms_page.edit"],
507    ),
508];
509
510/// Seed (or reconcile) the built-in MCP skills for one tenant. Idempotent:
511/// `create_skill_pool` is create-only, so on `Duplicate` we reconcile by
512/// adding any tool rows a newer CMS version introduced (never removing —
513/// operator customizations survive); the skill↔permission mappings are
514/// idempotent upserts.
515pub async fn ensure_mcp_skills(pool: &rustango::sql::Pool) -> Result<(), rustango::sql::ExecError> {
516    use rustango::core::Column as _;
517    use rustango::sql::FetcherPool as _;
518    use rustango::tenancy::{AgentSkill, AgentSkillTool};
519
520    for (codename, name, description, instructions, tools, perms) in MCP_SKILLS {
521        let tool_names: Vec<String> = tools.iter().map(|t| (*t).to_owned()).collect();
522        match rustango::tenancy::create_skill_pool(
523            pool,
524            codename,
525            name,
526            description,
527            instructions,
528            &tool_names,
529        )
530        .await
531        {
532            Ok(_) => {}
533            Err(rustango::tenancy::AgentError::Duplicate(_)) => {
534                // Reconcile: insert tool rows this CMS version added.
535                let skill: Option<AgentSkill> = AgentSkill::objects()
536                    .where_(AgentSkill::codename.eq((*codename).to_owned()))
537                    .first(pool)
538                    .await?;
539                let Some(skill) = skill else { continue };
540                let skill_id = skill.id.get().copied().unwrap_or_default();
541                let existing: Vec<AgentSkillTool> = AgentSkillTool::objects()
542                    .where_(AgentSkillTool::skill_id.eq(skill_id))
543                    .fetch(pool)
544                    .await?;
545                for tool in *tools {
546                    if !existing.iter().any(|t| t.tool_name == *tool) {
547                        let mut row = AgentSkillTool {
548                            id: rustango::sql::Auto::Unset,
549                            skill_id,
550                            tool_name: (*tool).to_owned(),
551                        };
552                        row.insert_pool(pool).await?;
553                    }
554                }
555            }
556            Err(e) => {
557                tracing::warn!(skill = codename, error = %e, "mcp skill create failed");
558                continue;
559            }
560        }
561        for perm in *perms {
562            if let Err(e) =
563                rustango::tenancy::map_skill_to_permission_pool(pool, codename, perm).await
564            {
565                tracing::warn!(skill = codename, perm, error = %e, "skill-permission map failed");
566            }
567        }
568    }
569    Ok(())
570}
571
572/// Seed three baseline roles per tenant so the permissions matrix is
573/// usable without an admin having to hand-craft codenames:
574///
575/// - **Viewer** — `view` on every resource except Users + Roles.
576/// - **Editor** — view/add/edit on content + media + library +
577///   redirects + navigation; view-only on locales / page types /
578///   settings / history; no Users/Roles access.
579/// - **Administrator** — every codename in the matrix.
580///
581/// Skipped per-role when a row with the same name exists, so
582/// admins can rename / retune the codename set without it being
583/// overwritten on the next boot.
584async fn ensure_default_roles(pool: &rustango::sql::Pool) -> Result<(), ExecError> {
585    use crate::admin::resources::{all_resources, codename};
586    use crate::permissions::Action;
587
588    let resources = all_resources();
589
590    // Helper: codenames matching a predicate on `(resource, action)`.
591    //
592    // Deduplicated, because two resources may legitimately share a
593    // `codename_prefix` — an app can point several admin pages at one
594    // permission, as a host app does to give its database and API
595    // connection screens a single verb. Each is
596    // its own row in the matrix, so `codename()` yields the same string
597    // twice, and `(role_id, codename)` is UNIQUE.
598    let collect = |pred: &dyn Fn(&crate::admin::resources::AdminResource, Action) -> bool| {
599        let mut out: Vec<String> = Vec::new();
600        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
601        for r in &resources {
602            for action in r.actions {
603                if pred(r, *action) {
604                    let code = codename(r, *action);
605                    if seen.insert(code.clone()) {
606                        out.push(code);
607                    }
608                }
609            }
610        }
611        out
612    };
613
614    let viewer_codes = collect(&|r, a| {
615        // Allow viewing every CRUD resource, plus the `cms_admin`
616        // access verb so they can actually open the admin. The
617        // `auth.access_admin` framework-admin verb stays off —
618        // Viewers shouldn't see the raw-DB-CRUD framework admin.
619        (a == Action::View
620            && r.codename_prefix != "rustango_users"
621            && r.codename_prefix != "rustango_roles")
622            || (a == Action::Access && r.codename_prefix == "cms_admin")
623    });
624    let editor_codes = collect(&|r, a| {
625        // No Users/Roles access at all.
626        if r.codename_prefix == "rustango_users" || r.codename_prefix == "rustango_roles" {
627            return false;
628        }
629        if r.codename_prefix == "cms_admin" {
630            return a == Action::Access;
631        }
632        // Editors don't get framework-admin access either — content
633        // workflow only.
634        if r.codename_prefix == "auth" {
635            return false;
636        }
637        match r.codename_prefix.as_str() {
638            // Always view-only here even if more actions are declared.
639            "cms_locale" | "cms_page_type" | "cms_history" => a == Action::View,
640            // Settings: view + edit.
641            "cms_settings" => matches!(a, Action::View | Action::Edit),
642            // Default: view/add/edit but no delete/publish on content.
643            _ => matches!(a, Action::View | Action::Add | Action::Edit),
644        }
645    });
646    // Administrator grants every codename across every section. With
647    // the `auth.access_admin` row now in the matrix (#10), this
648    // includes framework-admin access — Administrators get to do
649    // raw-DB-CRUD via /admin/ + CMS workflow via /cms-admin/.
650    let admin_codes = collect(&|_r, _a| true);
651
652    seed_role_with_codenames(
653        pool,
654        "Viewer",
655        "Read-only access across the admin.",
656        &viewer_codes,
657    )
658    .await?;
659    seed_role_with_codenames(
660        pool,
661        "Editor",
662        "Create / edit content, media, redirects, navigation. No access to users or roles.",
663        &editor_codes,
664    )
665    .await?;
666    seed_role_with_codenames(
667        pool,
668        "Administrator",
669        "Full access across every admin section.",
670        &admin_codes,
671    )
672    .await?;
673    // #559/#561 — Developer role: content modelling. Everything a Viewer
674    // sees, plus the page-type field builder (`cms_page_type.build`, a
675    // free-form codename the matrix preserves as legacy — it hard-gates
676    // the builder sub-router server-side).
677    let mut dev_codes = viewer_codes.clone();
678    dev_codes.push("cms_page_type.build".to_owned());
679    // Per-tenant template overrides. Same reasoning as the builder: it is
680    // content *modelling*, not content, so Developer gets it and the
681    // content roles do not.
682    dev_codes.push(crate::admin::TEMPLATE_EDIT_CODENAME.to_owned());
683    dev_codes.push(crate::admin::NOTIFICATION_MANAGE_CODENAME.to_owned());
684    // Binding a hostname changes what the public internet resolves to —
685    // deployment work, so it sits with the Developer/Administrator pair
686    // rather than with the content roles.
687    dev_codes.push(crate::admin::SITE_MANAGE_CODENAME.to_owned());
688    seed_role_with_codenames(
689        pool,
690        "Developer",
691        "Content modelling: build page-type field schemas + reusable components.",
692        &dev_codes,
693    )
694    .await?;
695    // Backfill (#35): when a role already exists from a previous seed
696    // run, idempotently add the `cms_admin.access` codename so users
697    // assigned to the seeded roles aren't suddenly locked out after
698    // upgrading to a build that enforces the gate.
699    backfill_codename(pool, "Viewer", "cms_admin.access").await?;
700    backfill_codename(pool, "Editor", "cms_admin.access").await?;
701    backfill_codename(pool, "Administrator", "cms_admin.access").await?;
702    // Backfill (#10): give Administrator the framework-admin access
703    // codename `auth.access_admin` (rustango#311 enforces this on
704    // `/__admin/` + `/admin/`). Viewers + Editors stay out of the
705    // raw-DB-CRUD framework admin by design.
706    backfill_codename(pool, "Administrator", "auth.access_admin").await?;
707    // #561 — existing installs: give Developer + Administrator the
708    // builder codename on upgrade.
709    backfill_codename(pool, "Developer", "cms_admin.access").await?;
710    backfill_codename(pool, "Developer", "cms_page_type.build").await?;
711    backfill_codename(pool, "Administrator", "cms_page_type.build").await?;
712    // Template editor: same two roles, so an upgrade doesn't leave the
713    // section visible to nobody.
714    backfill_codename(pool, "Developer", crate::admin::TEMPLATE_EDIT_CODENAME).await?;
715    backfill_codename(pool, "Administrator", crate::admin::TEMPLATE_EDIT_CODENAME).await?;
716    // Existing sites get it too — a permission that only reaches tenants
717    // created after the release is a permission most sites never have.
718    backfill_codename(pool, "Developer", crate::admin::NOTIFICATION_MANAGE_CODENAME).await?;
719    backfill_codename(pool, "Administrator", crate::admin::NOTIFICATION_MANAGE_CODENAME).await?;
720    backfill_codename(pool, "Developer", crate::admin::SITE_MANAGE_CODENAME).await?;
721    backfill_codename(pool, "Administrator", crate::admin::SITE_MANAGE_CODENAME).await?;
722    Ok(())
723}
724
725/// Add `codename` to the role named `role_name` if missing. No-op
726/// when the role doesn't exist or the codename is already present.
727async fn backfill_codename(
728    pool: &rustango::sql::Pool,
729    role_name: &str,
730    codename: &str,
731) -> Result<(), ExecError> {
732    use rustango::core::Column as _;
733    let role: Option<rustango::tenancy::permissions::Role> =
734        rustango::tenancy::permissions::Role::objects()
735            .where_(rustango::tenancy::permissions::Role::name.eq(role_name.to_owned()))
736            .first(pool)
737            .await?;
738    let Some(role) = role else {
739        return Ok(());
740    };
741    let role_id = role.id.get().copied().unwrap_or_default();
742    let existing: Vec<rustango::tenancy::permissions::RolePermission> =
743        rustango::tenancy::permissions::RolePermission::objects()
744            .where_(rustango::tenancy::permissions::RolePermission::role_id.eq(role_id))
745            .where_(
746                rustango::tenancy::permissions::RolePermission::codename.eq(codename.to_owned()),
747            )
748            .fetch(pool)
749            .await?;
750    if !existing.is_empty() {
751        return Ok(());
752    }
753    let mut perm = rustango::tenancy::permissions::RolePermission {
754        id: Auto::Unset,
755        role_id,
756        codename: codename.to_owned(),
757    };
758    perm.insert_pool(pool).await?;
759    Ok(())
760}
761
762async fn seed_role_with_codenames(
763    pool: &rustango::sql::Pool,
764    name: &str,
765    description: &str,
766    codenames: &[String],
767) -> Result<(), ExecError> {
768    use rustango::core::Column as _;
769    let existing: Vec<rustango::tenancy::permissions::Role> =
770        rustango::tenancy::permissions::Role::objects()
771            .where_(rustango::tenancy::permissions::Role::name.eq(name.to_owned()))
772            .fetch(pool)
773            .await?;
774    if existing.into_iter().next().is_some() {
775        return Ok(());
776    }
777    let mut row = rustango::tenancy::permissions::Role {
778        id: Auto::Unset,
779        name: name.to_owned(),
780        description: description.to_owned(),
781        data: serde_json::Value::Object(serde_json::Map::new()),
782    };
783    row.insert_pool(pool).await?;
784    let role_id = row.id.get().copied().unwrap_or_default();
785    // A role's permissions are a set. Callers assemble these lists by
786    // walking the resource matrix, where one codename can be reached by
787    // more than one route, and `(role_id, codename)` is UNIQUE — so a
788    // repeat is a constraint violation that aborts the whole seed, and
789    // with it the boot. Enforce the set here rather than trusting every
790    // caller to have done it.
791    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
792    for codename in codenames {
793        if !seen.insert(codename.as_str()) {
794            continue;
795        }
796        let mut perm = rustango::tenancy::permissions::RolePermission {
797            id: Auto::Unset,
798            role_id,
799            codename: codename.clone(),
800        };
801        perm.insert_pool(pool).await?;
802    }
803    Ok(())
804}
805
806/// Seed a single "Root" collection if the tenant has no
807/// `cms_media_collection` rows yet. New uploads default to it; the
808/// admin shows orphan media (NULL `collection_id`) under it too.
809/// Seed a default `en` locale when the tenant has none, so the
810/// "exactly one is_default" invariant holds from first boot.
811/// Idempotent: no-op once any locale row exists.
812async fn ensure_default_locale(pool: &rustango::sql::Pool) -> Result<(), ExecError> {
813    let existing: Vec<crate::locale::Locale> = crate::locale::Locale::objects().fetch(pool).await?;
814    if !existing.is_empty() {
815        return Ok(());
816    }
817    let mut row = crate::locale::Locale {
818        id: Auto::Unset,
819        code: "en".to_owned(),
820        name: "English".to_owned(),
821        is_default: true,
822        active: true,
823        sort_order: 0,
824        created_at: Auto::Unset,
825    };
826    row.insert_pool(pool).await?;
827    Ok(())
828}
829
830async fn ensure_root_media_collection(pool: &rustango::sql::Pool) -> Result<(), ExecError> {
831    let existing: Vec<crate::media::MediaCollection> =
832        crate::media::MediaCollection::objects().fetch(pool).await?;
833    if !existing.is_empty() {
834        return Ok(());
835    }
836    let mut row = crate::media::MediaCollection {
837        id: Auto::Unset,
838        name: "Root".to_owned(),
839        parent_id: None,
840        sort_order: 0,
841        created_at: Auto::Unset,
842    };
843    row.insert_pool(pool).await?;
844    Ok(())
845}
846
847/// Upsert a single `cms_page_type` row keyed by `type_name`.
848///
849/// Find-or-create rather than ON CONFLICT because the macro-emitted
850/// `upsert_on()` would conflict on the surrogate primary key — we
851/// want resolution by the `type_name` natural-key column.
852async fn upsert_page_type(
853    pool: &rustango::sql::Pool,
854    handler: &dyn PageTypeHandler,
855) -> Result<(), ExecError> {
856    let parents_json = serde_json::to_value(handler.allowed_parent_types())
857        .unwrap_or(serde_json::Value::Array(Vec::new()));
858    let children_json = serde_json::to_value(handler.allowed_child_types())
859        .unwrap_or(serde_json::Value::Array(Vec::new()));
860
861    let mut existing: Vec<PageType> = PageType::objects()
862        .where_(PageType::type_name.eq(handler.type_name().to_string()))
863        .fetch(pool)
864        .await?;
865
866    if let Some(mut row) = existing.pop() {
867        row.app_label = handler.app_label().to_owned();
868        row.verbose_name = handler.verbose_name().to_owned();
869        row.default_template = handler.default_template().to_owned();
870        row.view_mode = handler.view_mode().as_str().to_owned();
871        row.is_creatable = handler.is_creatable();
872        row.allowed_parent_types = parents_json;
873        row.allowed_child_types = children_json;
874        row.workflow = handler.workflow_slug().unwrap_or_default().to_owned();
875        row.save_pool(pool).await?;
876    } else {
877        let mut row = PageType {
878            id: Auto::Unset,
879            app_label: handler.app_label().to_owned(),
880            type_name: handler.type_name().to_owned(),
881            verbose_name: handler.verbose_name().to_owned(),
882            default_template: handler.default_template().to_owned(),
883            view_mode: handler.view_mode().as_str().to_owned(),
884            is_creatable: handler.is_creatable(),
885            allowed_parent_types: parents_json,
886            allowed_child_types: children_json,
887            workflow: handler.workflow_slug().unwrap_or_default().to_owned(),
888            created_at: Auto::Unset,
889            updated_at: Auto::Unset,
890        };
891        row.insert_pool(pool).await?;
892    }
893    Ok(())
894}
895
896/// Bring every form's managed email target up to date with its settings.
897///
898/// # Errors
899/// Driver / query failures.
900async fn reconcile_form_notification_targets(
901    pool: &rustango::sql::Pool,
902) -> Result<(), rustango::sql::ExecError> {
903    use rustango::core::Column as _;
904    use rustango::sql::FetcherPool as _;
905    let forms: Vec<crate::snippet::Snippet> = crate::snippet::Snippet::objects()
906        .where_(crate::snippet::Snippet::type_name.eq("form".to_owned()))
907        .fetch(pool)
908        .await?;
909    for f in forms {
910        let id = f.id.get().copied().unwrap_or_default();
911        let parsed = crate::forms::schema::parse_draft(&f.data);
912        crate::notify::targets::sync_form_email(
913            pool,
914            id,
915            &f.title,
916            &parsed.settings.notify_emails,
917        )
918        .await?;
919    }
920    Ok(())
921}
922
923#[cfg(all(test, feature = "sqlite"))]
924mod tests {
925    // `Column` (for `.eq`) and `FetcherPool` (for `.fetch` / `.first`)
926    // arrive through the glob — the module already imports both.
927    use super::*;
928    use rustango::core::Model as _;
929    use rustango::sql::Pool;
930    use rustango::tenancy::permissions::{Role, RolePermission};
931
932    async fn mem_pool() -> Pool {
933        let pool = Pool::connect("sqlite::memory:")
934            .await
935            .expect("in-memory sqlite");
936        for schema in [&Role::SCHEMA, &RolePermission::SCHEMA] {
937            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
938                pool.dialect(),
939                schema,
940            );
941            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
942                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
943                    .await
944                    .expect("ddl");
945            }
946        }
947        pool
948    }
949
950    /// A repeated codename must not reach the database twice.
951    ///
952    /// The lists these roles are seeded from are assembled by walking the
953    /// admin resource matrix, and one codename can be reached by more
954    /// than one route: an app may point several admin pages at a single
955    /// permission, as a host app does to give its database and API
956    /// connection screens one verb.
957    /// `(role_id, codename)` is UNIQUE, so before this was deduplicated
958    /// the second insert aborted the seed — and on a fresh tenant that
959    /// meant the application would not finish booting.
960    #[tokio::test]
961    async fn a_repeated_codename_is_granted_once() {
962        let pool = mem_pool().await;
963
964        seed_role_with_codenames(
965            &pool,
966            "Administrator",
967            "every codename",
968            &[
969                "rpt_connection.view".to_owned(),
970                "cms_page.view".to_owned(),
971                // The same permission, reached through a second admin page.
972                "rpt_connection.view".to_owned(),
973            ],
974        )
975        .await
976        .expect("seeding a role must tolerate a repeated codename");
977
978        let role: Role = Role::objects()
979            .where_(Role::name.eq("Administrator".to_owned()))
980            .first(&pool)
981            .await
982            .expect("query")
983            .expect("the role was created");
984        let role_id = role.id.get().copied().unwrap_or_default();
985
986        let granted: Vec<RolePermission> = RolePermission::objects()
987            .where_(RolePermission::role_id.eq(role_id))
988            .fetch(&pool)
989            .await
990            .expect("query");
991
992        assert_eq!(granted.len(), 2, "one row per distinct codename");
993        let mut codes: Vec<&str> = granted.iter().map(|p| p.codename.as_str()).collect();
994        codes.sort_unstable();
995        assert_eq!(codes, ["cms_page.view", "rpt_connection.view"]);
996    }
997}