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