Skip to main content

kanidmd_lib/server/
migrations.rs

1use crate::prelude::*;
2
3use crate::migration_data;
4use kanidm_proto::internal::{
5    // DomainUpgradeCheckItem as ProtoDomainUpgradeCheckItem,
6    DomainUpgradeCheckReport as ProtoDomainUpgradeCheckReport,
7    // DomainUpgradeCheckStatus as ProtoDomainUpgradeCheckStatus,
8};
9
10use super::ServerPhase;
11
12impl QueryServer {
13    #[instrument(level = "info", name = "system_initialisation", skip_all)]
14    pub async fn initialise_helper(
15        &self,
16        ts: Duration,
17        domain_target_level: DomainVersion,
18    ) -> Result<(), OperationError> {
19        // We need to perform this in a single transaction pass to prevent tainting
20        // databases during upgrades.
21        let mut write_txn = self.write(ts).await?;
22
23        // Because we init the schema here, and commit, this reloads meaning
24        // that the on-disk index meta has been loaded, so our subsequent
25        // migrations will be correctly indexed.
26        //
27        // Remember, that this would normally mean that it's possible for schema
28        // to be mis-indexed (IE we index the new schemas here before we read
29        // the schema to tell us what's indexed), but because we have the in
30        // mem schema that defines how schema is structured, and this is all
31        // marked "system", then we won't have an issue here.
32        if domain_target_level < DOMAIN_LEVEL_1_11 {
33            // Check our database version - attempt to do an initial indexing
34            // based on the in memory configuration. This ONLY triggers ONCE on
35            // the very first run of the instance when the DB in newely created.
36            //
37            // NOTE: After DL_1_11 this is no longer needed since all the schema
38            // is in memory, and we don't need these initial indexes in order
39            // to speed up index loading.
40            write_txn.upgrade_reindex(SYSTEM_INDEX_VERSION)?;
41
42            // We don't create these in the DB after 1_11
43            write_txn
44                .initialise_schema_core()
45                .and_then(|_| write_txn.reload())?;
46        }
47
48        // This is what tells us if the domain entry existed before or not. This
49        // is now the primary method of migrations and version detection.
50        let db_domain_version = match write_txn.internal_search_uuid(UUID_DOMAIN_INFO) {
51            Ok(e) => Ok(e.get_ava_single_uint32(Attribute::Version).unwrap_or(0)),
52            Err(OperationError::NoMatchingEntries) => Ok(0),
53            Err(r) => Err(r),
54        }?;
55
56        debug!(?db_domain_version, "Before setting internal domain info");
57
58        if db_domain_version == DOMAIN_LEVEL_0 {
59            // This is here to catch when we increase domain levels but didn't create the migration
60            // hooks. If this fails it probably means you need to add another migration hook
61            // in the above.
62            debug_assert!(domain_target_level <= DOMAIN_MAX_LEVEL);
63
64            // Assert that we have a minimum creation level that is valid.
65            const { assert!(DOMAIN_MIN_CREATION_LEVEL == DOMAIN_LEVEL_12) };
66
67            // No domain info was present, so neither was the rest of the IDM. Bring up the
68            // full IDM here.
69
70            match domain_target_level {
71                DOMAIN_LEVEL_12 => write_txn.migrate_domain_11_to_12()?,
72                DOMAIN_LEVEL_13 => write_txn.migrate_domain_12_to_13()?,
73                DOMAIN_LEVEL_14 => write_txn.migrate_domain_13_to_14()?,
74                DOMAIN_LEVEL_1_11 => write_txn.migrate_domain_1_10_to_1_11()?,
75                DOMAIN_LEVEL_1_12 => write_txn.migrate_domain_1_11_to_1_12()?,
76                DOMAIN_LEVEL_1_13 => write_txn.migrate_domain_1_12_to_1_13()?,
77                DOMAIN_LEVEL_1_14 => write_txn.migrate_domain_1_13_to_1_14()?,
78                _ => {
79                    error!("Invalid requested domain target level for server bootstrap");
80                    debug_assert!(false);
81                    return Err(OperationError::MG0009InvalidTargetLevelForBootstrap);
82                }
83            }
84
85            write_txn
86                .internal_apply_domain_migration(domain_target_level)
87                .map(|()| {
88                    warn!(
89                        "Domain level has been bootstrapped to {}",
90                        domain_target_level
91                    );
92                })?;
93        }
94
95        // These steps apply both to bootstrapping and normal startup, since we now have
96        // a DB with data populated in either path.
97
98        // Domain info is now present, so we need to reflect that in our server
99        // domain structures. If we don't do this, the in memory domain level
100        // is stuck at 0 which can confuse init domain info below.
101        //
102        // This also is where the former domain taint flag will be loaded to
103        // d_info so that if the *previous* execution of the database was
104        // a devel version, we'll still trigger the forced remigration in
105        // in the case that we are moving from dev -> stable.
106        write_txn.force_domain_reload();
107
108        write_txn.reload()?;
109
110        assert!(write_txn.get_domain_version() > DOMAIN_LEVEL_0);
111
112        // Indicate the schema is now ready, which allows dyngroups to work when they
113        // are created in the next phase of migrations.
114        write_txn.set_phase(ServerPhase::SchemaReady);
115
116        // #2756 - if we *aren't* creating the base IDM entries, then we
117        // need to force dyn groups to reload since we're now at schema
118        // ready. This is done indirectly by ... reloading the schema again.
119        //
120        // This is because dyngroups don't load until server phase >= schemaready
121        // and the reload path for these is either a change in the dyngroup entry
122        // itself or a change to schema reloading. Since we aren't changing the
123        // dyngroup here, we have to go via the schema reload path.
124        write_txn.force_schema_reload();
125
126        // Reload as init idm affects access controls.
127        write_txn.reload()?;
128
129        // Domain info is now ready and reloaded, we can proceed.
130        write_txn.set_phase(ServerPhase::DomainInfoReady);
131
132        // This is the start of domain info related migrations which we will need in future
133        // to handle replication. Due to the access control rework, and the addition of "managed by"
134        // syntax, we need to ensure both nodes "fence" replication from each other. We do this
135        // by changing domain infos to be incompatible during this phase.
136
137        // The reloads will have populated this structure now.
138        let domain_info_version = write_txn.get_domain_version();
139        let domain_patch_level = write_txn.get_domain_patch_level();
140        let domain_development_taint = write_txn.get_domain_development_taint();
141        debug!(
142            ?db_domain_version,
143            ?domain_patch_level,
144            ?domain_development_taint,
145            "After setting internal domain info"
146        );
147
148        let mut reload_required = false;
149
150        // If the database domain info is a lower version than our target level, we reload.
151        if domain_info_version < domain_target_level {
152            // if (domain_target_level - domain_info_version) > DOMAIN_MIGRATION_SKIPS {
153            if domain_info_version < DOMAIN_MIGRATION_FROM_MIN {
154                error!(
155                    "UNABLE TO PROCEED. You are attempting a skip update which is NOT SUPPORTED."
156                );
157                error!(
158                    "For more see: https://kanidm.github.io/kanidm/stable/support.html#upgrade-policy and https://kanidm.github.io/kanidm/stable/server_updates.html"
159                );
160                error!(domain_previous_version = ?domain_info_version, domain_target_version = ?domain_target_level, domain_migration_minimum_limit = ?DOMAIN_MIGRATION_FROM_MIN);
161                return Err(OperationError::MG0008SkipUpgradeAttempted);
162            }
163
164            // Apply each step in order.
165            for domain_target_level_step in domain_info_version..domain_target_level {
166                // Rust has no way to do a range with the minimum excluded and the maximum
167                // included, so we have to do min -> max which includes min and excludes max,
168                // and by adding 1 we gett the same result.
169                let domain_target_level_step = domain_target_level_step + 1;
170
171                // Note that this triggers a reload for us, we don't need to manually determine if
172                // one is needed or not.
173                write_txn
174                    .internal_apply_domain_migration(domain_target_level_step)
175                    .map(|()| {
176                        warn!(
177                            "Domain level has been raised to {}",
178                            domain_target_level_step
179                        );
180                    })?;
181            }
182        } else if domain_info_version > domain_target_level {
183            // This is a DOWNGRADE which may not proceed.
184            error!("UNABLE TO PROCEED. You are attempting a downgrade which is NOT SUPPORTED.");
185            error!(
186                "For more see: https://kanidm.github.io/kanidm/stable/support.html#upgrade-policy and https://kanidm.github.io/kanidm/stable/server_updates.html"
187            );
188            error!(domain_previous_version = ?domain_info_version, domain_target_version = ?domain_target_level);
189            return Err(OperationError::MG0010DowngradeNotAllowed);
190        } else if domain_development_taint {
191            // This forces pre-release versions to re-migrate each start up. This solves
192            // the domain-version-sprawl issue so that during a development cycle we can
193            // do a single domain version bump, and continue to extend the migrations
194            // within that release cycle to contain what we require.
195            //
196            // If this is a pre-release build
197            // AND
198            // we are NOT in a test environment
199            // AND
200            // We did not already need a version migration as above
201            write_txn.domain_remigrate(DOMAIN_PREVIOUS_TGT_LEVEL)?;
202
203            reload_required = true;
204        }
205
206        // If we are new enough to support patches, and we are lower than the target patch level
207        // then a reload will be applied after we raise the patch level.
208        if domain_patch_level < DOMAIN_TGT_PATCH_LEVEL {
209            write_txn
210                .internal_modify_uuid(
211                    UUID_DOMAIN_INFO,
212                    &ModifyList::new_purge_and_set(
213                        Attribute::PatchLevel,
214                        Value::new_uint32(DOMAIN_TGT_PATCH_LEVEL),
215                    ),
216                )
217                .map(|()| {
218                    warn!(
219                        "Domain patch level has been raised to {}",
220                        domain_patch_level
221                    );
222                })?;
223
224            reload_required = true;
225        };
226
227        // Execute whatever operations we have batched up and ready to go. This is needed
228        // to preserve ordering of the operations - if we reloaded after a remigrate then
229        // we would have skipped the patch level fix which needs to have occurred *first*.
230        if reload_required {
231            write_txn.reload()?;
232        }
233
234        // Now set the db/domain devel taint flag to match our current release status
235        // if it changes. This is what breaks the cycle of db taint from dev -> stable
236        let current_devel_flag = option_env!("KANIDM_PRE_RELEASE").is_some();
237        if current_devel_flag {
238            warn!("Domain Development Taint mode is enabled");
239        }
240        if domain_development_taint != current_devel_flag {
241            write_txn.internal_modify_uuid(
242                UUID_DOMAIN_INFO,
243                &ModifyList::new_purge_and_set(
244                    Attribute::DomainDevelopmentTaint,
245                    Value::Bool(current_devel_flag),
246                ),
247            )?;
248        }
249
250        // We are ready to run
251        write_txn.set_phase(ServerPhase::Running);
252
253        // Commit all changes, this also triggers the final reload, this should be a no-op
254        // since we already did all the needed loads above.
255        write_txn.commit()?;
256
257        debug!("Database version check and migrations success! ☀️  ");
258        Ok(())
259    }
260}
261
262impl QueryServerWriteTransaction<'_> {
263    /// Apply a domain migration `to_level`. Errors if `to_level` is not greater than or equal to
264    /// the active level.
265    #[instrument(level = "debug", skip(self))]
266    pub(crate) fn internal_apply_domain_migration(
267        &mut self,
268        to_level: u32,
269    ) -> Result<(), OperationError> {
270        self.internal_modify_uuid(
271            UUID_DOMAIN_INFO,
272            &ModifyList::new_purge_and_set(Attribute::Version, Value::new_uint32(to_level)),
273        )
274        .and_then(|()| self.reload())
275    }
276
277    fn internal_migrate_or_create_batch(
278        &mut self,
279        msg: &str,
280        entries: Vec<EntryInitNew>,
281    ) -> Result<(), OperationError> {
282        let r: Result<(), _> = entries
283            .into_iter()
284            .try_for_each(|entry| self.internal_migrate_or_create(entry));
285
286        if let Err(err) = r {
287            error!(?err, msg);
288            debug_assert!(false);
289        }
290
291        Ok(())
292    }
293
294    #[instrument(level = "debug", skip_all)]
295    /// - If the thing exists:
296    ///   - Ensure the set of attributes match and are present
297    ///     (but don't delete multivalue, or extended attributes in the situation.
298    /// - If not:
299    ///   - Create the entry
300    ///
301    /// This will extra classes an attributes alone!
302    ///
303    /// NOTE: `gen_modlist*` IS schema aware and will handle multivalue correctly!
304    fn internal_migrate_or_create(
305        &mut self,
306        e: Entry<EntryInit, EntryNew>,
307    ) -> Result<(), OperationError> {
308        // NOTE: Ignoring an attribute only affects the migration phase, not create.
309        self.internal_migrate_or_create_ignore_attrs(
310            e,
311            &[
312                // If the credential type is present, we don't want to touch it.
313                Attribute::CredentialTypeMinimum,
314            ],
315        )
316    }
317
318    #[instrument(level = "debug", skip_all)]
319    fn internal_delete_batch(
320        &mut self,
321        msg: &str,
322        entries: Vec<Uuid>,
323    ) -> Result<(), OperationError> {
324        let filter = entries
325            .into_iter()
326            .map(|uuid| f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)))
327            .collect();
328
329        // Don't attempt to delete already removed entries that are in the recycle bin.
330        let filter = filter!(f_or(filter));
331
332        let result = self.internal_delete(&filter);
333
334        match result {
335            Ok(_) | Err(OperationError::NoMatchingEntries) => Ok(()),
336            Err(err) => {
337                error!(?err, msg);
338                Err(err)
339            }
340        }
341    }
342
343    /// This is the same as [QueryServerWriteTransaction::internal_migrate_or_create]
344    /// but it will ignore the specified list of attributes, so that if an admin has
345    /// modified those values then we don't stomp them.
346    #[instrument(level = "trace", skip_all)]
347    fn internal_migrate_or_create_ignore_attrs(
348        &mut self,
349        mut e: Entry<EntryInit, EntryNew>,
350        attrs: &[Attribute],
351    ) -> Result<(), OperationError> {
352        debug!("operating on {:?}", e.get_display_id());
353        trace!(?e, ?attrs);
354
355        let Some(filt) = e.filter_from_attrs(&[Attribute::Uuid]) else {
356            return Err(OperationError::FilterGeneration);
357        };
358
359        trace!("search {:?}", filt);
360
361        let results = self.internal_search(filt.clone())?;
362
363        if results.is_empty() {
364            // The entry does not exist. Create it.
365
366            // If there are create-once members, set them up now.
367            if let Some(members_create_once) = e.pop_ava(Attribute::MemberCreateOnce) {
368                if let Some(members) = e.get_ava_mut(Attribute::Member) {
369                    // Merge
370                    members.merge(&members_create_once).inspect_err(|err| {
371                        error!(?err, "Unable to merge member sets, mismatched types?");
372                    })?;
373                } else {
374                    // Just push
375                    e.set_ava_set(&Attribute::Member, members_create_once);
376                }
377            };
378
379            self.internal_create(vec![e])
380        } else if results.len() == 1 {
381            // This is always ignored during migration.
382            e.remove_ava(&Attribute::MemberCreateOnce);
383
384            // For each ignored attr, we remove it from entry.
385            for attr in attrs.iter() {
386                e.remove_ava(attr);
387            }
388
389            // If the thing is subset, pass
390            match e.gen_modlist_assert(&self.schema) {
391                Ok(modlist) => {
392                    // Apply to &results[0]
393                    trace!(?modlist);
394                    self.internal_modify(&filt, &modlist)
395                }
396                Err(e) => Err(OperationError::SchemaViolation(e)),
397            }
398        } else {
399            admin_error!(
400                "Invalid Result Set - Expected One Entry for {:?} - {:?}",
401                filt,
402                results
403            );
404            Err(OperationError::InvalidDbState)
405        }
406    }
407
408    // Commented as an example of patch application
409    /*
410    /// Patch Application - This triggers a one-shot fixup task for issue #3178
411    /// to force access controls to re-migrate in existing databases so that they're
412    /// content matches expected values.
413    #[instrument(level = "info", skip_all)]
414    pub(crate) fn migrate_domain_patch_level_2(&mut self) -> Result<(), OperationError> {
415        admin_warn!("applying domain patch 2.");
416
417        debug_assert!(*self.phase >= ServerPhase::SchemaReady);
418
419        let idm_data = migration_data::dl9::phase_7_builtin_access_control_profiles();
420
421        idm_data
422            .into_iter()
423            .try_for_each(|entry| self.internal_migrate_or_create(entry))
424            .map_err(|err| {
425                error!(?err, "migrate_domain_patch_level_2 -> Error");
426                err
427            })?;
428
429        self.reload()?;
430
431        Ok(())
432    }
433    */
434
435    /// Migration domain level 11 to 12 (1.8.0)
436    #[instrument(level = "info", skip_all)]
437    pub(crate) fn migrate_domain_11_to_12(&mut self) -> Result<(), OperationError> {
438        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_11 {
439            error!("Unable to raise domain level from 11 to 12.");
440            return Err(OperationError::MG0004DomainLevelInDevelopment);
441        }
442
443        // =========== Apply changes ==============
444        self.internal_migrate_or_create_batch(
445            "phase 1 - schema attrs",
446            migration_data::dl12::phase_1_schema_attrs(),
447        )?;
448
449        self.internal_migrate_or_create_batch(
450            "phase 2 - schema classes",
451            migration_data::dl12::phase_2_schema_classes(),
452        )?;
453
454        // Reload for the new schema.
455        self.reload()?;
456
457        // Since we just loaded in a ton of schema, lets reindex it in case we added
458        // new indexes, or this is a bootstrap and we have no indexes yet.
459        self.reindex(false)?;
460
461        // Set Phase
462        // Indicate the schema is now ready, which allows dyngroups to work when they
463        // are created in the next phase of migrations.
464        self.set_phase(ServerPhase::SchemaReady);
465
466        self.internal_migrate_or_create_batch(
467            "phase 3 - key provider",
468            migration_data::dl12::phase_3_key_provider(),
469        )?;
470
471        // Reload for the new key providers
472        self.reload()?;
473
474        self.internal_migrate_or_create_batch(
475            "phase 4 - system entries",
476            migration_data::dl12::phase_4_system_entries(),
477        )?;
478
479        // Reload for the new system entries
480        self.reload()?;
481
482        // Domain info is now ready and reloaded, we can proceed.
483        self.set_phase(ServerPhase::DomainInfoReady);
484
485        // Bring up the IDM entries.
486        self.internal_migrate_or_create_batch(
487            "phase 5 - builtin admin entries",
488            migration_data::dl12::phase_5_builtin_admin_entries()?,
489        )?;
490
491        self.internal_migrate_or_create_batch(
492            "phase 6 - builtin not admin entries",
493            migration_data::dl12::phase_6_builtin_non_admin_entries()?,
494        )?;
495
496        self.internal_migrate_or_create_batch(
497            "phase 7 - builtin access control profiles",
498            migration_data::dl12::phase_7_builtin_access_control_profiles(),
499        )?;
500
501        self.reload()?;
502
503        // Cleanup any leftover id keys
504        let modlist = ModifyList::new_purge(Attribute::IdVerificationEcKey);
505        let filter = filter_all!(f_pres(Attribute::IdVerificationEcKey));
506
507        self.internal_modify(&filter, &modlist)?;
508
509        Ok(())
510    }
511
512    /// Migration domain level 12 to 13 (1.9.0)
513    #[instrument(level = "info", skip_all)]
514    pub(crate) fn migrate_domain_12_to_13(&mut self) -> Result<(), OperationError> {
515        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_12 {
516            error!("Unable to raise domain level from 12 to 13.");
517            return Err(OperationError::MG0004DomainLevelInDevelopment);
518        }
519
520        // =========== Apply changes ==============
521        self.internal_migrate_or_create_batch(
522            "phase 1 - schema attrs",
523            migration_data::dl13::phase_1_schema_attrs(),
524        )?;
525
526        self.internal_migrate_or_create_batch(
527            "phase 2 - schema classes",
528            migration_data::dl13::phase_2_schema_classes(),
529        )?;
530
531        // Reload for the new schema.
532        self.reload()?;
533
534        // Since we just loaded in a ton of schema, lets reindex it in case we added
535        // new indexes, or this is a bootstrap and we have no indexes yet.
536        self.reindex(false)?;
537
538        // Set Phase
539        // Indicate the schema is now ready, which allows dyngroups to work when they
540        // are created in the next phase of migrations.
541        self.set_phase(ServerPhase::SchemaReady);
542
543        self.internal_migrate_or_create_batch(
544            "phase 3 - key provider",
545            migration_data::dl13::phase_3_key_provider(),
546        )?;
547
548        // Reload for the new key providers
549        self.reload()?;
550
551        self.internal_migrate_or_create_batch(
552            "phase 4 - system entries",
553            migration_data::dl13::phase_4_system_entries(),
554        )?;
555
556        // Reload for the new system entries
557        self.reload()?;
558
559        // Domain info is now ready and reloaded, we can proceed.
560        self.set_phase(ServerPhase::DomainInfoReady);
561
562        // Bring up the IDM entries.
563        self.internal_migrate_or_create_batch(
564            "phase 5 - builtin admin entries",
565            migration_data::dl13::phase_5_builtin_admin_entries()?,
566        )?;
567
568        self.internal_migrate_or_create_batch(
569            "phase 6 - builtin not admin entries",
570            migration_data::dl13::phase_6_builtin_non_admin_entries()?,
571        )?;
572
573        self.internal_migrate_or_create_batch(
574            "phase 7 - builtin access control profiles",
575            migration_data::dl13::phase_7_builtin_access_control_profiles(),
576        )?;
577
578        self.internal_delete_batch(
579            "phase 8 - delete UUIDS",
580            migration_data::dl13::phase_8_delete_uuids(),
581        )?;
582
583        self.reload()?;
584
585        Ok(())
586    }
587
588    /// Migration domain level 13 to 14 (1.10.0)
589    #[instrument(level = "info", skip_all)]
590    pub(crate) fn migrate_domain_13_to_14(&mut self) -> Result<(), OperationError> {
591        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_13 {
592            error!("Unable to raise domain level from 13 to 14.");
593            return Err(OperationError::MG0004DomainLevelInDevelopment);
594        }
595
596        // =========== Apply changes ==============
597        self.internal_migrate_or_create_batch(
598            &format!("phase 1 - schema attrs target {}", DOMAIN_TGT_LEVEL),
599            migration_data::dl14::phase_1_schema_attrs(),
600        )?;
601
602        self.internal_migrate_or_create_batch(
603            "phase 2 - schema classes",
604            migration_data::dl14::phase_2_schema_classes(),
605        )?;
606
607        // Reload for the new schema.
608        self.reload()?;
609
610        // Since we just loaded in a ton of schema, lets reindex it in case we added
611        // new indexes, or this is a bootstrap and we have no indexes yet.
612        self.reindex(false)?;
613
614        // Set Phase
615        // Indicate the schema is now ready, which allows dyngroups to work when they
616        // are created in the next phase of migrations.
617        self.set_phase(ServerPhase::SchemaReady);
618
619        self.internal_migrate_or_create_batch(
620            "phase 3 - key provider",
621            migration_data::dl14::phase_3_key_provider(),
622        )?;
623
624        // Reload for the new key providers
625        self.reload()?;
626
627        self.internal_migrate_or_create_batch(
628            "phase 4 - dl14 system entries",
629            migration_data::dl14::phase_4_system_entries(),
630        )?;
631
632        // Reload for the new system entries
633        self.reload()?;
634
635        // Domain info is now ready and reloaded, we can proceed.
636        self.set_phase(ServerPhase::DomainInfoReady);
637
638        // Bring up the IDM entries.
639        self.internal_migrate_or_create_batch(
640            "phase 5 - builtin admin entries",
641            migration_data::dl14::phase_5_builtin_admin_entries()?,
642        )?;
643
644        self.internal_migrate_or_create_batch(
645            "phase 6 - builtin not admin entries",
646            migration_data::dl14::phase_6_builtin_non_admin_entries()?,
647        )?;
648
649        self.internal_migrate_or_create_batch(
650            "phase 7 - builtin access control profiles",
651            migration_data::dl14::phase_7_builtin_access_control_profiles(),
652        )?;
653
654        self.internal_delete_batch(
655            "phase 8 - delete UUIDS",
656            migration_data::dl14::phase_8_delete_uuids(),
657        )?;
658
659        self.reload()?;
660
661        // Default PasswordChangedTime to UNIX_EPOCH
662        let filter = filter_all!(f_and!([
663            f_eq(Attribute::Class, EntryClass::Person.into()),
664            f_andnot(f_pres(Attribute::PasswordChangedTime)),
665        ]));
666        let modlist = ModifyList::new_purge_and_set(
667            Attribute::PasswordChangedTime,
668            Value::DateTime(time::OffsetDateTime::UNIX_EPOCH),
669        );
670        self.internal_modify(&filter, &modlist)?;
671
672        Ok(())
673    }
674
675    pub(crate) fn migrate_schema_1_11(&mut self) -> Result<(), OperationError> {
676        // Flag that the schema changes - this is important because now that the
677        // schema is in memory only, the on-disk triggers won't fire now.
678        self.force_schema_reload();
679
680        self.schema.extend_in_memory(
681            migration_data::dl15::phase_1_schema_attrs(),
682            migration_data::dl15::phase_2_schema_classes(),
683        )
684    }
685
686    /// Migration domain level 14 to 15 (1.11.0)
687    #[instrument(level = "info", skip_all)]
688    pub(crate) fn migrate_domain_1_10_to_1_11(&mut self) -> Result<(), OperationError> {
689        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_14 {
690            error!(
691                "Unable to raise domain level from {} to {}.",
692                DOMAIN_LEVEL_14, DOMAIN_LEVEL_1_11
693            );
694            return Err(OperationError::MG0004DomainLevelInDevelopment);
695        }
696
697        // =========== Apply changes ==============
698        self.migrate_schema_1_11()?;
699
700        // Reload for the new schema.
701        self.reload()?;
702
703        // Since we just loaded in a ton of schema, lets reindex it in case we added
704        // new indexes, or this is a bootstrap and we have no indexes yet.
705        self.reindex(false)?;
706
707        // Delete all existing DB contained schema.
708
709        let filter = filter!(f_and(vec![
710            f_eq(Attribute::Class, EntryClass::ClassType.into()),
711            f_eq(Attribute::Class, EntryClass::AttributeType.into()),
712        ]));
713
714        self.internal_delete_if_exists(&filter)?;
715
716        // Set Phase
717        // Indicate the schema is now ready, which allows dyngroups to work when they
718        // are created in the next phase of migrations.
719        self.set_phase(ServerPhase::SchemaReady);
720
721        self.internal_migrate_or_create_batch(
722            "phase 3 - key provider",
723            migration_data::dl15::phase_3_key_provider(),
724        )?;
725
726        // Reload for the new key providers
727        self.reload()?;
728
729        self.internal_migrate_or_create_batch(
730            "phase 4 - dl15 system entries",
731            migration_data::dl15::phase_4_system_entries(),
732        )?;
733
734        // Reload for the new system entries
735        self.reload()?;
736
737        // Domain info is now ready and reloaded, we can proceed.
738        self.set_phase(ServerPhase::DomainInfoReady);
739
740        // Bring up the IDM entries.
741        self.internal_migrate_or_create_batch(
742            "phase 5 - builtin admin entries",
743            migration_data::dl15::phase_5_builtin_admin_entries()?,
744        )?;
745
746        self.internal_migrate_or_create_batch(
747            "phase 6 - builtin not admin entries",
748            migration_data::dl15::phase_6_builtin_non_admin_entries()?,
749        )?;
750
751        self.internal_migrate_or_create_batch(
752            "phase 7 - builtin access control profiles",
753            migration_data::dl15::phase_7_builtin_access_control_profiles(),
754        )?;
755
756        self.internal_delete_batch(
757            "phase 8 - delete UUIDS",
758            migration_data::dl15::phase_8_delete_uuids(),
759        )?;
760
761        self.reload()?;
762
763        // Default PasswordChangedTime to UNIX_EPOCH
764        let filter = filter_all!(f_and!([
765            f_eq(Attribute::Class, EntryClass::Person.into()),
766            f_andnot(f_pres(Attribute::PasswordChangedTime)),
767        ]));
768        let modlist = ModifyList::new_purge_and_set(
769            Attribute::PasswordChangedTime,
770            Value::DateTime(time::OffsetDateTime::UNIX_EPOCH),
771        );
772        self.internal_modify(&filter, &modlist)?;
773
774        Ok(())
775    }
776
777    pub(crate) fn migrate_schema_1_12(&mut self) -> Result<(), OperationError> {
778        // Flag that the schema changes - this is important because now that the
779        // schema is in memory only, the on-disk triggers won't fire now.
780        self.force_schema_reload();
781
782        self.schema.extend_in_memory(
783            migration_data::dl_1_12::phase_1_schema_attrs(),
784            migration_data::dl_1_12::phase_2_schema_classes(),
785        )
786    }
787
788    /// Migration domain level 1.11 to 1.12
789    #[instrument(level = "info", skip_all)]
790    pub(crate) fn migrate_domain_1_11_to_1_12(&mut self) -> Result<(), OperationError> {
791        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_1_12 {
792            error!("Unable to raise domain level from 1_11 to 1_12.");
793            return Err(OperationError::MG0004DomainLevelInDevelopment);
794        }
795
796        use migration_data::dl_1_12 as dl_target;
797
798        if self.get_phase() >= ServerPhase::DomainInfoReady {
799            // Rewrite all entries in place to cause them to re-write their on disk format.
800            let filter = filter_all!(f_or!([
801                // Uuid
802                f_pres(Attribute::DomainUuid),
803                f_pres(Attribute::InMemoriam),
804                f_pres(Attribute::OAuth2AccountCredentialUuid),
805                f_pres(Attribute::Uuid),
806                f_pres(Attribute::CascadeDeleted),
807                // Refer
808                f_pres(Attribute::KeyProvider),
809                f_pres(Attribute::LinkedGroup),
810                f_pres(Attribute::SyncParentUuid),
811                f_pres(Attribute::Refers),
812                f_pres(Attribute::OAuth2AccountProvider),
813                f_pres(Attribute::EntryManagedBy),
814                // Iutf8
815                f_pres(Attribute::LoginShell),
816                f_pres(Attribute::DomainLdapBasedn),
817                f_pres(Attribute::AttributeName),
818                f_pres(Attribute::ClassName),
819                f_pres(Attribute::SyncExternalId),
820                // Iname
821                f_pres(Attribute::DomainName),
822                f_pres(Attribute::OAuth2RsName),
823                f_pres(Attribute::Name),
824                // Url
825                f_pres(Attribute::ApplicationUrl),
826                f_pres(Attribute::OAuth2RsOriginLanding),
827                f_pres(Attribute::OAuth2TokenEndpoint),
828                f_pres(Attribute::SyncCredentialPortal),
829                f_pres(Attribute::OAuth2AuthorisationEndpoint),
830                f_pres(Attribute::OAuth2TokenIntrospectEndpoint),
831            ]));
832
833            let mut entries = self.internal_search_writeable(&filter)?;
834
835            // Migrate the formerly multivalue types to single value types.
836            for (_, entry) in entries.iter_mut() {
837                for attr in [
838                    // Uuid
839                    Attribute::DomainUuid,
840                    Attribute::InMemoriam,
841                    Attribute::OAuth2AccountCredentialUuid,
842                    Attribute::Uuid,
843                    Attribute::CascadeDeleted,
844                    // Refer
845                    Attribute::KeyProvider,
846                    Attribute::LinkedGroup,
847                    Attribute::SyncParentUuid,
848                    Attribute::Refers,
849                    Attribute::OAuth2AccountProvider,
850                    Attribute::EntryManagedBy,
851                    // Iutf8
852                    Attribute::LoginShell,
853                    Attribute::DomainLdapBasedn,
854                    Attribute::AttributeName,
855                    Attribute::ClassName,
856                    Attribute::SyncExternalId,
857                    // Iname
858                    Attribute::DomainName,
859                    Attribute::OAuth2RsName,
860                    Attribute::Name,
861                    // Url
862                    Attribute::ApplicationUrl,
863                    Attribute::OAuth2RsOriginLanding,
864                    Attribute::OAuth2TokenEndpoint,
865                    Attribute::SyncCredentialPortal,
866                    Attribute::OAuth2AuthorisationEndpoint,
867                    Attribute::OAuth2TokenIntrospectEndpoint,
868                ] {
869                    entry.migrate_ava(attr)?;
870                }
871            }
872
873            let count = entries.len();
874
875            self.internal_apply_writable(entries)?;
876
877            debug!("Updated DB format for {} entries", count);
878        }
879
880        // =========== Apply changes ==============
881        self.migrate_schema_1_12()?;
882
883        // Reload for the new schema.
884        self.reload()?;
885
886        // Since we just loaded in a ton of schema, lets reindex it in case we added
887        // new indexes, or this is a bootstrap and we have no indexes yet.
888        self.reindex(false)?;
889
890        // Delete all existing DB contained schema.
891
892        let filter = filter!(f_and(vec![
893            f_eq(Attribute::Class, EntryClass::ClassType.into()),
894            f_eq(Attribute::Class, EntryClass::AttributeType.into()),
895        ]));
896
897        self.internal_delete_if_exists(&filter)?;
898
899        // Set Phase
900        // Indicate the schema is now ready, which allows dyngroups to work when they
901        // are created in the next phase of migrations.
902        self.set_phase(ServerPhase::SchemaReady);
903
904        self.internal_migrate_or_create_batch(
905            "phase 3 - key provider",
906            dl_target::phase_3_key_provider(),
907        )?;
908
909        // Reload for the new key providers
910        self.reload()?;
911
912        self.internal_migrate_or_create_batch(
913            "phase 4 - system entries",
914            dl_target::phase_4_system_entries(),
915        )?;
916
917        // Reload for the new system entries
918        self.reload()?;
919
920        // Domain info is now ready and reloaded, we can proceed.
921        self.set_phase(ServerPhase::DomainInfoReady);
922
923        // Bring up the IDM entries.
924        self.internal_migrate_or_create_batch(
925            "phase 5 - builtin admin entries",
926            dl_target::phase_5_builtin_admin_entries()?,
927        )?;
928
929        self.internal_migrate_or_create_batch(
930            "phase 6 - builtin not admin entries",
931            dl_target::phase_6_builtin_non_admin_entries()?,
932        )?;
933
934        self.internal_migrate_or_create_batch(
935            "phase 7 - builtin access control profiles",
936            dl_target::phase_7_builtin_access_control_profiles(),
937        )?;
938
939        self.internal_delete_batch("phase 8 - delete UUIDS", dl_target::phase_8_delete_uuids())?;
940
941        self.reload()?;
942
943        let filter = filter_all!(f_and!([f_eq(
944            Attribute::Class,
945            EntryClass::OAuth2ResourceServer.into()
946        ),]));
947        let modlist =
948            ModifyList::new_append(Attribute::Class, EntryClass::KeyObjectJweA256GCM.into());
949        self.internal_modify(&filter, &modlist)?;
950
951        Ok(())
952    }
953
954    pub(crate) fn migrate_schema_1_13(&mut self) -> Result<(), OperationError> {
955        // Flag that the schema changes - this is important because now that the
956        // schema is in memory only, the on-disk triggers won't fire now.
957        self.force_schema_reload();
958
959        self.schema.extend_in_memory(
960            migration_data::dl_1_13::phase_1_schema_attrs(),
961            migration_data::dl_1_13::phase_2_schema_classes(),
962        )
963    }
964
965    /// Migration domain level 1.12 to 1.13
966    #[instrument(level = "info", skip_all)]
967    pub(crate) fn migrate_domain_1_12_to_1_13(&mut self) -> Result<(), OperationError> {
968        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_1_13 {
969            error!("Unable to raise domain level from 1_12 to 1_13.");
970            return Err(OperationError::MG0004DomainLevelInDevelopment);
971        }
972
973        use migration_data::dl_1_13 as dl_target;
974
975        // =========== Apply changes ==============
976        self.migrate_schema_1_13()?;
977
978        // Reload for the new schema.
979        self.reload()?;
980
981        // Since we just loaded in a ton of schema, lets reindex it in case we added
982        // new indexes, or this is a bootstrap and we have no indexes yet.
983        self.reindex(false)?;
984
985        // Set Phase
986        // Indicate the schema is now ready, which allows dyngroups to work when they
987        // are created in the next phase of migrations.
988        self.set_phase(ServerPhase::SchemaReady);
989
990        self.internal_migrate_or_create_batch(
991            "phase 3 - key provider",
992            dl_target::phase_3_key_provider(),
993        )?;
994
995        // Reload for the new key providers
996        self.reload()?;
997
998        self.internal_migrate_or_create_batch(
999            "phase 4 - system entries",
1000            dl_target::phase_4_system_entries(),
1001        )?;
1002
1003        // Reload for the new system entries
1004        self.reload()?;
1005
1006        // Domain info is now ready and reloaded, we can proceed.
1007        self.set_phase(ServerPhase::DomainInfoReady);
1008
1009        // Bring up the IDM entries.
1010        self.internal_migrate_or_create_batch(
1011            "phase 5 - builtin admin entries",
1012            dl_target::phase_5_builtin_admin_entries()?,
1013        )?;
1014
1015        self.internal_migrate_or_create_batch(
1016            "phase 6 - builtin not admin entries",
1017            dl_target::phase_6_builtin_non_admin_entries()?,
1018        )?;
1019
1020        self.internal_migrate_or_create_batch(
1021            "phase 7 - builtin access control profiles",
1022            dl_target::phase_7_builtin_access_control_profiles(),
1023        )?;
1024
1025        self.internal_delete_batch("phase 8 - delete UUIDS", dl_target::phase_8_delete_uuids())?;
1026
1027        self.reload()?;
1028
1029        Ok(())
1030    }
1031
1032    /// Migration domain level 1.12 to 1.13
1033    #[instrument(level = "info", skip_all)]
1034    pub(crate) fn migrate_domain_1_13_to_1_14(&mut self) -> Result<(), OperationError> {
1035        if !cfg!(test) && DOMAIN_TGT_LEVEL < DOMAIN_LEVEL_1_14 {
1036            error!("Unable to raise domain level from 1_13 to 1_14.");
1037            return Err(OperationError::MG0004DomainLevelInDevelopment);
1038        }
1039
1040        Ok(())
1041    }
1042
1043    #[instrument(level = "info", skip_all)]
1044    pub(crate) fn initialise_schema_core(&mut self) -> Result<(), OperationError> {
1045        debug!("initialise_schema_core -> start ...");
1046        // Load in all the "core" schema, that we already have in "memory".
1047        let entries = self.schema.to_entries();
1048
1049        // admin_debug!("Dumping schemas: {:?}", entries);
1050
1051        // internal_migrate_or_create.
1052        let r: Result<_, _> = entries.into_iter().try_for_each(|e| {
1053            trace!(?e, "init schema entry");
1054            self.internal_migrate_or_create(e)
1055        });
1056        if r.is_ok() {
1057            debug!("initialise_schema_core -> Ok!");
1058        } else {
1059            error!(?r, "initialise_schema_core -> Error");
1060        }
1061        // why do we have error handling if it's always supposed to be `Ok`?
1062        debug_assert!(r.is_ok());
1063        r
1064    }
1065}
1066
1067impl QueryServerReadTransaction<'_> {
1068    /// Retrieve the domain info of this server
1069    pub fn domain_upgrade_check(
1070        &mut self,
1071    ) -> Result<ProtoDomainUpgradeCheckReport, OperationError> {
1072        let d_info = &self.d_info;
1073
1074        let name = d_info.d_name.clone();
1075        let uuid = d_info.d_uuid;
1076        let current_level = d_info.d_vers;
1077        let upgrade_level = DOMAIN_TGT_NEXT_LEVEL;
1078
1079        let report_items = Vec::with_capacity(1);
1080
1081        // Intentionally left commented to serve as a future check template.
1082        /*
1083        if current_level <= DOMAIN_LEVEL_7 && upgrade_level >= DOMAIN_LEVEL_8 {
1084            let item = self
1085                .domain_upgrade_check_7_to_8_oauth2_strict_redirect_uri()
1086                .map_err(|err| {
1087                    error!(
1088                        ?err,
1089                        "Failed to perform domain upgrade check 7 to 8 - oauth2-strict-redirect_uri"
1090                    );
1091                    err
1092                })?;
1093            report_items.push(item);
1094        }
1095        */
1096
1097        Ok(ProtoDomainUpgradeCheckReport {
1098            name,
1099            uuid,
1100            current_level,
1101            upgrade_level,
1102            report_items,
1103        })
1104    }
1105
1106    // Intentionally left commented to serve as a future check template.
1107    /*
1108    pub(crate) fn domain_upgrade_check_7_to_8_oauth2_strict_redirect_uri(
1109        &mut self,
1110    ) -> Result<ProtoDomainUpgradeCheckItem, OperationError> {
1111        let filter = filter!(f_and!([
1112            f_eq(Attribute::Class, EntryClass::OAuth2ResourceServer.into()),
1113            f_andnot(f_pres(Attribute::OAuth2StrictRedirectUri)),
1114        ]));
1115
1116        let results = self.internal_search(filter)?;
1117
1118        let affected_entries = results
1119            .into_iter()
1120            .map(|entry| entry.get_display_id())
1121            .collect::<Vec<_>>();
1122
1123        let status = if affected_entries.is_empty() {
1124            ProtoDomainUpgradeCheckStatus::Pass7To8Oauth2StrictRedirectUri
1125        } else {
1126            ProtoDomainUpgradeCheckStatus::Fail7To8Oauth2StrictRedirectUri
1127        };
1128
1129        Ok(ProtoDomainUpgradeCheckItem {
1130            status,
1131            from_level: DOMAIN_LEVEL_7,
1132            to_level: DOMAIN_LEVEL_8,
1133            affected_entries,
1134        })
1135    }
1136    */
1137}
1138
1139#[cfg(test)]
1140mod tests {
1141    // use super::{ProtoDomainUpgradeCheckItem, ProtoDomainUpgradeCheckStatus};
1142    use crate::{prelude::*, value::CredentialType, valueset::ValueSetCredentialType};
1143
1144    #[qs_test]
1145    async fn test_init_idempotent_schema_core(server: &QueryServer) {
1146        {
1147            // Setup and abort.
1148            let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
1149            assert!(server_txn.initialise_schema_core().is_ok());
1150        }
1151        {
1152            let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
1153            assert!(server_txn.initialise_schema_core().is_ok());
1154            assert!(server_txn.initialise_schema_core().is_ok());
1155            assert!(server_txn.commit().is_ok());
1156        }
1157        {
1158            // Now do it again in a new txn, but abort
1159            let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
1160            assert!(server_txn.initialise_schema_core().is_ok());
1161        }
1162        {
1163            // Now do it again in a new txn.
1164            let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
1165            assert!(server_txn.initialise_schema_core().is_ok());
1166            assert!(server_txn.commit().is_ok());
1167        }
1168    }
1169
1170    /// This test is for ongoing/longterm checks over the previous to current version.
1171    /// This is in contrast to the specific version checks below that are often to
1172    /// test a version to version migration.
1173    #[qs_test(domain_level=DOMAIN_PREVIOUS_TGT_LEVEL)]
1174    async fn test_migrations_dl_previous_to_dl_target(server: &QueryServer) {
1175        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1176
1177        let db_domain_version = write_txn
1178            .internal_search_uuid(UUID_DOMAIN_INFO)
1179            .expect("unable to access domain entry")
1180            .get_ava_single_uint32(Attribute::Version)
1181            .expect("Attribute Version not present");
1182
1183        assert_eq!(db_domain_version, DOMAIN_PREVIOUS_TGT_LEVEL);
1184
1185        // == SETUP ==
1186
1187        // Add a member to a group - it should not be removed.
1188        // Remove a default member from a group - it should be returned.
1189        let modlist = ModifyList::new_set(
1190            Attribute::Member,
1191            // This achieves both because this removes IDM_ADMIN from the group
1192            // while setting only anon as a member.
1193            ValueSetReferN::new(UUID_ANONYMOUS),
1194        );
1195        write_txn
1196            .internal_modify_uuid(UUID_IDM_ADMINS, &modlist)
1197            .expect("Unable to modify CredentialTypeMinimum");
1198
1199        // Remove a group from an object that is "create once".  It should not
1200        // be re-added.
1201        let modlist = ModifyList::new_purge(Attribute::Member);
1202        write_txn
1203            .internal_modify_uuid(UUID_IDM_PEOPLE_SELF_NAME_WRITE, &modlist)
1204            .expect("Unable to remove idm_all_persons from self-write");
1205
1206        // Change default account policy - it should not be reverted.
1207        let modlist = ModifyList::new_set(
1208            Attribute::CredentialTypeMinimum,
1209            ValueSetCredentialType::new(CredentialType::Any),
1210        );
1211        write_txn
1212            .internal_modify_uuid(UUID_IDM_ALL_PERSONS, &modlist)
1213            .expect("Unable to modify CredentialTypeMinimum");
1214
1215        write_txn.commit().expect("Unable to commit");
1216
1217        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1218
1219        // == Increase the version ==
1220        write_txn
1221            .internal_apply_domain_migration(DOMAIN_TGT_LEVEL)
1222            .expect("Unable to set domain level");
1223
1224        // post migration verification.
1225        // Check that our group is as we left it
1226        let idm_admins_entry = write_txn
1227            .internal_search_uuid(UUID_IDM_ADMINS)
1228            .expect("Unable to retrieve all persons");
1229
1230        debug!(?idm_admins_entry);
1231
1232        let members = idm_admins_entry
1233            .get_ava_refer(Attribute::Member)
1234            .expect("No members present");
1235
1236        // Still present
1237        assert!(members.contains(&UUID_ANONYMOUS));
1238        // Was reverted
1239        assert!(members.contains(&UUID_IDM_ADMIN));
1240
1241        // Check that self-write still doesn't have all persons.
1242        let idm_people_self_name_write_entry = write_txn
1243            .internal_search_uuid(UUID_IDM_PEOPLE_SELF_NAME_WRITE)
1244            .expect("Unable to retrieve all persons");
1245
1246        let members = idm_people_self_name_write_entry.get_ava_refer(Attribute::Member);
1247
1248        // There are no members!
1249        assert!(members.is_none());
1250
1251        // Check that the account policy did not revert.
1252        let all_persons_entry = write_txn
1253            .internal_search_uuid(UUID_IDM_ALL_PERSONS)
1254            .expect("Unable to retrieve all persons");
1255
1256        assert_eq!(
1257            all_persons_entry.get_ava_single_credential_type(Attribute::CredentialTypeMinimum),
1258            Some(CredentialType::Any)
1259        );
1260
1261        write_txn.commit().expect("Unable to commit");
1262    }
1263
1264    #[qs_test(domain_level=DOMAIN_TGT_LEVEL)]
1265    async fn test_migrations_prevent_downgrades(server: &QueryServer) {
1266        let curtime = duration_from_epoch_now();
1267
1268        let mut write_txn = server.write(curtime).await.unwrap();
1269
1270        let db_domain_version = write_txn
1271            .internal_search_uuid(UUID_DOMAIN_INFO)
1272            .expect("unable to access domain entry")
1273            .get_ava_single_uint32(Attribute::Version)
1274            .expect("Attribute Version not present");
1275
1276        assert_eq!(db_domain_version, DOMAIN_TGT_LEVEL);
1277
1278        drop(write_txn);
1279
1280        // MUST NOT SUCCEED.
1281        let err = server
1282            .initialise_helper(curtime, DOMAIN_PREVIOUS_TGT_LEVEL)
1283            .await
1284            .expect_err("Domain level was lowered!!!!");
1285
1286        assert_eq!(err, OperationError::MG0010DowngradeNotAllowed);
1287    }
1288
1289    #[qs_test(domain_level=DOMAIN_MIGRATION_FROM_INVALID)]
1290    async fn test_migrations_prevent_skips(server: &QueryServer) {
1291        let curtime = duration_from_epoch_now();
1292
1293        let mut write_txn = server.write(curtime).await.unwrap();
1294
1295        let db_domain_version = write_txn
1296            .internal_search_uuid(UUID_DOMAIN_INFO)
1297            .expect("unable to access domain entry")
1298            .get_ava_single_uint32(Attribute::Version)
1299            .expect("Attribute Version not present");
1300
1301        assert_eq!(db_domain_version, DOMAIN_MIGRATION_FROM_INVALID);
1302
1303        drop(write_txn);
1304
1305        // MUST NOT SUCCEED.
1306        let err = server
1307            .initialise_helper(curtime, DOMAIN_TGT_LEVEL)
1308            .await
1309            .expect_err("Migration went ahead!!!!");
1310
1311        assert_eq!(err, OperationError::MG0008SkipUpgradeAttempted);
1312    }
1313
1314    #[qs_test(domain_level=DOMAIN_MIGRATION_FROM_MIN)]
1315    async fn test_migrations_skip_valid(server: &QueryServer) {
1316        let curtime = duration_from_epoch_now();
1317        // This is a smoke test that X -> Z migrations work for some range. This doesn't
1318        // absolve us of the need to write more detailed migration tests.
1319        let mut write_txn = server.write(curtime).await.unwrap();
1320
1321        let db_domain_version = write_txn
1322            .internal_search_uuid(UUID_DOMAIN_INFO)
1323            .expect("unable to access domain entry")
1324            .get_ava_single_uint32(Attribute::Version)
1325            .expect("Attribute Version not present");
1326
1327        assert_eq!(db_domain_version, DOMAIN_MIGRATION_FROM_MIN);
1328
1329        drop(write_txn);
1330
1331        // MUST SUCCEED.
1332        server
1333            .initialise_helper(curtime, DOMAIN_TGT_LEVEL)
1334            .await
1335            .expect("Migration failed!!!!")
1336    }
1337
1338    #[qs_test(domain_level=DOMAIN_LEVEL_12)]
1339    async fn test_migrations_dl12_dl13(server: &QueryServer) {
1340        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1341
1342        let db_domain_version = write_txn
1343            .internal_search_uuid(UUID_DOMAIN_INFO)
1344            .expect("unable to access domain entry")
1345            .get_ava_single_uint32(Attribute::Version)
1346            .expect("Attribute Version not present");
1347
1348        assert_eq!(db_domain_version, DOMAIN_LEVEL_12);
1349
1350        write_txn.commit().expect("Unable to commit");
1351
1352        // == pre migration verification. ==
1353        // check we currently would fail a migration.
1354
1355        // let mut read_txn = server.read().await.unwrap();
1356        // drop(read_txn);
1357
1358        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1359
1360        // Fix any issues
1361
1362        // == Increase the version ==
1363        write_txn
1364            .internal_apply_domain_migration(DOMAIN_LEVEL_13)
1365            .expect("Unable to set domain level to version 13");
1366
1367        // post migration verification.
1368
1369        write_txn.commit().expect("Unable to commit");
1370    }
1371
1372    #[qs_test(domain_level=DOMAIN_LEVEL_13)]
1373    async fn test_migrations_dl13_dl14(server: &QueryServer) {
1374        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1375
1376        let db_domain_version = write_txn
1377            .internal_search_uuid(UUID_DOMAIN_INFO)
1378            .expect("unable to access domain entry")
1379            .get_ava_single_uint32(Attribute::Version)
1380            .expect("Attribute Version not present");
1381
1382        assert_eq!(db_domain_version, DOMAIN_LEVEL_13);
1383
1384        // Create a person without pwd_changed_time
1385        let tuuid = Uuid::new_v4();
1386        let e1 = entry_init!(
1387            (Attribute::Class, EntryClass::Object.to_value()),
1388            (Attribute::Class, EntryClass::Person.to_value()),
1389            (Attribute::Class, EntryClass::Account.to_value()),
1390            (Attribute::Name, Value::new_iname("testperson1")),
1391            (Attribute::Uuid, Value::Uuid(tuuid)),
1392            (Attribute::Description, Value::new_utf8s("testperson1")),
1393            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
1394        );
1395
1396        write_txn
1397            .internal_create(vec![e1])
1398            .expect("Unable to create test person");
1399
1400        let user = write_txn
1401            .internal_search_uuid(tuuid)
1402            .expect("Unable to load test person");
1403
1404        // sanity check
1405        assert!(user
1406            .get_ava_single_datetime(Attribute::PasswordChangedTime)
1407            .is_none());
1408
1409        write_txn.commit().expect("Unable to commit");
1410
1411        // == pre migration verification. ==
1412        // check we currently would fail a migration.
1413
1414        // let mut read_txn = server.read().await.unwrap();
1415        // drop(read_txn);
1416
1417        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1418
1419        // Fix any issues
1420
1421        // == Increase the version ==
1422        write_txn
1423            .internal_apply_domain_migration(DOMAIN_LEVEL_14)
1424            .expect("Unable to set domain level to version 14");
1425
1426        // post migration verification.
1427        // pwd_changed_time should be defaulted to UNIX_EPOCH
1428        let user = write_txn
1429            .internal_search_uuid(tuuid)
1430            .expect("Unable to load test person after migration");
1431
1432        let pwd_changed = user
1433            .get_ava_single_datetime(Attribute::PasswordChangedTime)
1434            .expect("PasswordChangedTime should be set after DL13->DL14 migration");
1435
1436        assert_eq!(pwd_changed, time::OffsetDateTime::UNIX_EPOCH);
1437
1438        write_txn.commit().expect("Unable to commit");
1439    }
1440
1441    #[qs_test(domain_level=DOMAIN_LEVEL_14)]
1442    async fn test_migrations_dl14_dl1_11(server: &QueryServer) {
1443        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1444
1445        let db_domain_version = write_txn
1446            .internal_search_uuid(UUID_DOMAIN_INFO)
1447            .expect("unable to access domain entry")
1448            .get_ava_single_uint32(Attribute::Version)
1449            .expect("Attribute Version not present");
1450
1451        assert_eq!(db_domain_version, DOMAIN_LEVEL_14);
1452
1453        write_txn.commit().expect("Unable to commit");
1454
1455        // == pre migration verification. ==
1456        // check we currently would fail a migration.
1457
1458        // let mut read_txn = server.read().await.unwrap();
1459        // drop(read_txn);
1460
1461        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1462
1463        // Fix any issues
1464
1465        // == Increase the version ==
1466        write_txn
1467            .internal_apply_domain_migration(DOMAIN_LEVEL_1_11)
1468            .expect("Unable to set domain level to version 1_11");
1469
1470        // post migration verification.
1471
1472        // Assert all lingering schema db entries are removed.
1473
1474        let filter = filter!(f_and(vec![
1475            f_eq(Attribute::Class, EntryClass::ClassType.into()),
1476            f_eq(Attribute::Class, EntryClass::AttributeType.into()),
1477        ]));
1478
1479        let entries_remain = write_txn.internal_exists(&filter).unwrap();
1480        assert!(!entries_remain);
1481
1482        write_txn.commit().expect("Unable to commit");
1483    }
1484
1485    #[qs_test(domain_level=DOMAIN_LEVEL_1_11)]
1486    async fn test_migrations_dl1_11_to_dl_1_12(server: &QueryServer) {
1487        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1488
1489        let db_domain_version = write_txn
1490            .internal_search_uuid(UUID_DOMAIN_INFO)
1491            .expect("unable to access domain entry")
1492            .get_ava_single_uint32(Attribute::Version)
1493            .expect("Attribute Version not present");
1494
1495        assert_eq!(db_domain_version, DOMAIN_LEVEL_1_11);
1496
1497        // Create an OAuth2 Client
1498
1499        let oauth2_client_uuid = Uuid::new_v4();
1500        let oauth2_client_entry = EntryInitNew::from_iter([
1501            (
1502                Attribute::Class,
1503                ValueSetIutf8N::from_iter([
1504                    EntryClass::Object.into(),
1505                    EntryClass::Account.into(),
1506                    EntryClass::OAuth2ResourceServer.into(),
1507                    EntryClass::OAuth2ResourceServerBasic.into(),
1508                ])
1509                .unwrap() as _,
1510            ),
1511            (Attribute::Name, ValueSetIname::new("test_oauth2_client")),
1512            (
1513                Attribute::DisplayName,
1514                vs_utf8!("test_oauth2_client".to_string()),
1515            ),
1516            (Attribute::Uuid, vs_uuid!(oauth2_client_uuid)),
1517            (
1518                Attribute::OAuth2RsOriginLanding,
1519                ValueSetUrl::new(Url::parse("https://demo.example.com").unwrap()) as ValueSet,
1520            ),
1521        ]);
1522
1523        write_txn
1524            .internal_create(vec![oauth2_client_entry])
1525            .expect("Unable to create entries");
1526
1527        let oauth2_client_entry_pre = write_txn
1528            .internal_search_uuid(oauth2_client_uuid)
1529            .expect("Unable to load oauth2 client");
1530
1531        // sanity check
1532        assert!(!oauth2_client_entry_pre.has_class(&EntryClass::KeyObjectJweA256GCM));
1533
1534        write_txn.commit().expect("Unable to commit");
1535
1536        // == pre migration verification. ==
1537        // check we currently would fail a migration.
1538
1539        // let mut read_txn = server.read().await.unwrap();
1540        // drop(read_txn);
1541
1542        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1543
1544        // Fix any issues
1545
1546        // == Increase the version ==
1547        write_txn
1548            .internal_apply_domain_migration(DOMAIN_LEVEL_1_12)
1549            .expect("Unable to set domain level to version 1_12");
1550
1551        // post migration verification.
1552        let oauth2_client_entry_pre = write_txn
1553            .internal_search_uuid(oauth2_client_uuid)
1554            .expect("Unable to load oauth2 client");
1555
1556        // Must now have the A256GCM class
1557        assert!(oauth2_client_entry_pre.has_class(&EntryClass::KeyObjectJweA256GCM));
1558
1559        write_txn.commit().expect("Unable to commit");
1560    }
1561
1562    #[qs_test(domain_level=DOMAIN_LEVEL_1_12)]
1563    async fn test_migrations_dl1_12_to_dl_1_13(server: &QueryServer) {
1564        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1565
1566        let db_domain_version = write_txn
1567            .internal_search_uuid(UUID_DOMAIN_INFO)
1568            .expect("unable to access domain entry")
1569            .get_ava_single_uint32(Attribute::Version)
1570            .expect("Attribute Version not present");
1571
1572        assert_eq!(db_domain_version, DOMAIN_LEVEL_1_12);
1573
1574        write_txn.commit().expect("Unable to commit");
1575
1576        // == pre migration verification. ==
1577        // check we currently would fail a migration.
1578
1579        // let mut read_txn = server.read().await.unwrap();
1580        // drop(read_txn);
1581
1582        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
1583
1584        // Fix any issues
1585
1586        // == Increase the version ==
1587        write_txn
1588            .internal_apply_domain_migration(DOMAIN_LEVEL_1_13)
1589            .expect("Unable to set domain level to version 1_13");
1590
1591        // post migration verification.
1592
1593        write_txn.commit().expect("Unable to commit");
1594    }
1595}