Skip to main content

kanidmd_lib/server/
mod.rs

1//! `server` contains the query server, which is the main high level construction
2//! to coordinate queries and operations in the server.
3
4use self::{
5    access::{
6        profiles::{
7            AccessControlCreate, AccessControlDelete, AccessControlModify, AccessControlSearch,
8        },
9        AccessControls, AccessControlsReadTransaction, AccessControlsTransaction,
10        AccessControlsWriteTransaction,
11    },
12    keys::{
13        KeyObject, KeyProvider, KeyProviders, KeyProvidersReadTransaction, KeyProvidersTransaction,
14        KeyProvidersWriteTransaction,
15    },
16};
17use crate::{
18    be::{Backend, BackendReadTransaction, BackendTransaction, BackendWriteTransaction},
19    filter::{
20        Filter, FilterInvalid, FilterValid, FilterValidResolved, ResolveFilterCache,
21        ResolveFilterCacheReadTxn,
22    },
23    plugins::{
24        self,
25        dyngroup::{DynGroup, DynGroupCache},
26        Plugins,
27    },
28    prelude::*,
29    repl::{cid::Cid, proto::ReplRuvRange, ruv::ReplicationUpdateVectorTransaction},
30    schema::{
31        Schema, SchemaAttribute, SchemaClass, SchemaReadTransaction, SchemaTransaction,
32        SchemaWriteTransaction,
33    },
34    value::{CredentialType, EXTRACT_VAL_DN},
35    valueset::*,
36};
37use concread::{
38    arcache::{ARCacheBuilder, ARCacheReadTxn, ARCacheWriteTxn},
39    cowcell::*,
40};
41use crypto_glue::{hmac_s256::HmacSha256Key, s256::Sha256Output};
42use hashbrown::{HashMap, HashSet};
43use kanidm_proto::{
44    internal::{DomainInfo as ProtoDomainInfo, ImageValue, UiHint},
45    scim_v1::{
46        server::{ScimListResponse, ScimOAuth2ClaimMap, ScimOAuth2ScopeMap, ScimReference},
47        JsonValue, ScimEntryGetQuery, ScimFilter,
48    },
49};
50use std::{
51    collections::{BTreeMap, BTreeSet},
52    num::NonZeroU64,
53    str::FromStr,
54    sync::Arc,
55};
56use time::OffsetDateTime;
57use tokio::sync::{Semaphore, SemaphorePermit};
58use tracing::trace;
59
60pub(crate) mod access;
61pub mod assert;
62pub mod batch_modify;
63pub mod create;
64pub mod delete;
65pub mod identity;
66pub(crate) mod keys;
67pub(crate) mod migrations;
68pub mod modify;
69pub(crate) mod recycle;
70pub mod scim;
71pub(crate) mod utils;
72
73const RESOLVE_FILTER_CACHE_MAX: usize = 256;
74const RESOLVE_FILTER_CACHE_LOCAL: usize = 8;
75
76#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq)]
77pub(crate) enum ServerPhase {
78    Bootstrap,
79    SchemaReady,
80    DomainInfoReady,
81    Running,
82}
83
84/// Domain Information. This should not contain sensitive information, the data within
85/// this structure may be used for public presentation.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct DomainInfo {
88    pub(crate) d_uuid: Uuid,
89    pub(crate) d_name: String,
90    pub(crate) d_display: String,
91    pub(crate) d_vers: DomainVersion,
92    pub(crate) d_patch_level: u32,
93    pub(crate) d_devel_taint: bool,
94    pub(crate) d_ldap_allow_unix_pw_bind: bool,
95    pub(crate) d_allow_easter_eggs: bool,
96    pub(crate) d_allow_account_recovery: bool,
97    // In future this should be image reference instead of the image itself.
98    d_image: Option<ImageValue>,
99
100    // Needs to be part of the domain structure so we can expose this to the UI.
101    feature_config: FeatureConfig,
102}
103
104impl DomainInfo {
105    pub fn name(&self) -> &str {
106        self.d_name.as_str()
107    }
108
109    pub fn display_name(&self) -> &str {
110        self.d_display.as_str()
111    }
112
113    pub fn devel_taint(&self) -> bool {
114        self.d_devel_taint
115    }
116
117    pub fn image(&self) -> Option<&ImageValue> {
118        self.d_image.as_ref()
119    }
120
121    pub fn has_custom_image(&self) -> bool {
122        self.d_image.is_some()
123    }
124
125    pub fn allow_easter_eggs(&self) -> bool {
126        self.d_allow_easter_eggs
127    }
128
129    pub fn allow_account_recovery(&self) -> bool {
130        self.d_allow_account_recovery
131    }
132
133    pub fn allow_account_signup(&self) -> bool {
134        self.feature_config.account_signup.enabled
135    }
136
137    #[cfg(feature = "test")]
138    pub fn new_test() -> CowCell<Self> {
139        concread::cowcell::CowCell::new(Self {
140            d_uuid: Uuid::new_v4(),
141            d_name: "test domain".to_string(),
142            d_display: "Test Domain".to_string(),
143            d_vers: 1,
144            d_patch_level: 0,
145            d_devel_taint: false,
146            d_ldap_allow_unix_pw_bind: false,
147            d_allow_easter_eggs: false,
148            d_allow_account_recovery: false,
149            d_image: None,
150            feature_config: FeatureConfig::default(),
151        })
152    }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Default)]
156pub struct SystemConfig {
157    pub(crate) denied_names: HashSet<String>,
158    pub(crate) pw_badlist: HashSet<String>,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Default)]
162pub struct HmacNameHistoryConfig {
163    pub(crate) enabled: bool,
164    pub(crate) key: HmacSha256Key,
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Default)]
168pub struct AccountSignupConfig {
169    pub(crate) enabled: bool,
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, Default)]
173pub struct FeatureConfig {
174    pub(crate) hmac_name_history: HmacNameHistoryConfig,
175    pub(crate) account_signup: AccountSignupConfig,
176}
177
178#[derive(Clone)]
179pub struct QueryServer {
180    phase: Arc<CowCell<ServerPhase>>,
181    pub(crate) d_info: Arc<CowCell<DomainInfo>>,
182    system_config: Arc<CowCell<SystemConfig>>,
183    be: Backend,
184    schema: Arc<Schema>,
185    accesscontrols: Arc<AccessControls>,
186    db_tickets: Arc<Semaphore>,
187    read_tickets: Arc<Semaphore>,
188    write_ticket: Arc<Semaphore>,
189    resolve_filter_cache: Arc<ResolveFilterCache>,
190    dyngroup_cache: Arc<CowCell<DynGroupCache>>,
191    cid_max: Arc<CowCell<Cid>>,
192    key_providers: Arc<KeyProviders>,
193}
194
195pub struct QueryServerReadTransaction<'a> {
196    be_txn: BackendReadTransaction<'a>,
197    // Anything else? In the future, we'll need to have a schema transaction
198    // type, maybe others?
199    pub(crate) d_info: CowCellReadTxn<DomainInfo>,
200    system_config: CowCellReadTxn<SystemConfig>,
201    schema: SchemaReadTransaction,
202    accesscontrols: AccessControlsReadTransaction<'a>,
203    key_providers: KeyProvidersReadTransaction,
204    _db_ticket: SemaphorePermit<'a>,
205    _read_ticket: SemaphorePermit<'a>,
206    resolve_filter_cache: ResolveFilterCacheReadTxn<'a>,
207    // Future we may need this.
208    // cid_max: CowCellReadTxn<Cid>,
209    trim_cid: Cid,
210    txn_name_to_uuid: BTreeMap<String, Uuid>,
211}
212
213unsafe impl Sync for QueryServerReadTransaction<'_> {}
214
215unsafe impl Send for QueryServerReadTransaction<'_> {}
216
217bitflags::bitflags! {
218    #[derive(Copy, Clone, Debug)]
219    pub struct ChangeFlag: u64 {
220        const SCHEMA =                      0b0000_0000_0000_0001;
221        const ACP =                         0b0000_0000_0000_0010;
222        const OAUTH2 =                      0b0000_0000_0000_0100;
223        const DOMAIN =                      0b0000_0000_0000_1000;
224        const SYSTEM_CONFIG =               0b0000_0000_0001_0000;
225        const SYNC_AGREEMENT =              0b0000_0000_0010_0000;
226        const KEY_MATERIAL   =              0b0000_0000_0100_0000;
227        const APPLICATION    =              0b0000_0000_1000_0000;
228        const OAUTH2_CLIENT            =    0b0000_0001_0000_0000;
229        const FEATURE                  =    0b0000_0010_0000_0000;
230    }
231}
232
233pub struct QueryServerWriteTransaction<'a> {
234    committed: bool,
235    phase: CowCellWriteTxn<'a, ServerPhase>,
236    d_info: CowCellWriteTxn<'a, DomainInfo>,
237    system_config: CowCellWriteTxn<'a, SystemConfig>,
238    curtime: Duration,
239    cid: CowCellWriteTxn<'a, Cid>,
240    trim_cid: Cid,
241    pub(crate) be_txn: BackendWriteTransaction<'a>,
242    pub(crate) schema: SchemaWriteTransaction<'a>,
243    accesscontrols: AccessControlsWriteTransaction<'a>,
244    key_providers: KeyProvidersWriteTransaction<'a>,
245    // We store a set of flags that indicate we need a reload of
246    // schema or acp, which is tested by checking the classes of the
247    // changing content.
248    pub(super) changed_flags: ChangeFlag,
249
250    // Store the list of changed uuids for other invalidation needs?
251    pub(super) changed_uuid: HashSet<Uuid>,
252    _db_ticket: SemaphorePermit<'a>,
253    _write_ticket: SemaphorePermit<'a>,
254    resolve_filter_cache_clear: bool,
255    resolve_filter_cache_write: ARCacheWriteTxn<
256        'a,
257        (IdentityId, Arc<Filter<FilterValid>>),
258        Arc<Filter<FilterValidResolved>>,
259        (),
260    >,
261    resolve_filter_cache: ARCacheReadTxn<
262        'a,
263        (IdentityId, Arc<Filter<FilterValid>>),
264        Arc<Filter<FilterValidResolved>>,
265        (),
266    >,
267    dyngroup_cache: CowCellWriteTxn<'a, DynGroupCache>,
268    txn_name_to_uuid: BTreeMap<String, Uuid>,
269}
270
271impl QueryServerWriteTransaction<'_> {
272    pub(crate) fn trim_cid(&self) -> &Cid {
273        &self.trim_cid
274    }
275}
276
277/// The `QueryServerTransaction` trait provides a set of common read only operations to be
278/// shared between [`QueryServerReadTransaction`] and [`QueryServerWriteTransaction`]s.
279///
280/// These operations tend to be high level constructions, generally different types of searches
281/// that are capable of taking different types of parameters and applying access controls or not,
282/// impersonating accounts, or bypassing these via internal searches.
283///
284/// [`QueryServerReadTransaction`]: struct.QueryServerReadTransaction.html
285/// [`QueryServerWriteTransaction`]: struct.QueryServerWriteTransaction.html
286pub trait QueryServerTransaction<'a> {
287    type BackendTransactionType: BackendTransaction;
288    fn get_be_txn(&mut self) -> &mut Self::BackendTransactionType;
289
290    type SchemaTransactionType: SchemaTransaction;
291    fn get_schema<'b>(&self) -> &'b Self::SchemaTransactionType;
292
293    type AccessControlsTransactionType: AccessControlsTransaction<'a>;
294    fn get_accesscontrols(&self) -> &Self::AccessControlsTransactionType;
295
296    type KeyProvidersTransactionType: KeyProvidersTransaction;
297    fn get_key_providers(&self) -> &Self::KeyProvidersTransactionType;
298
299    fn pw_badlist(&self) -> &HashSet<String>;
300
301    fn denied_names(&self) -> &HashSet<String>;
302
303    fn domain_info(&self) -> &DomainInfo;
304
305    fn get_domain_version(&self) -> DomainVersion;
306
307    fn get_domain_patch_level(&self) -> u32;
308
309    fn get_domain_development_taint(&self) -> bool;
310
311    fn get_domain_uuid(&self) -> Uuid;
312
313    fn get_domain_name(&self) -> &str;
314
315    fn get_domain_display_name(&self) -> &str;
316
317    fn get_domain_image_value(&self) -> Option<ImageValue>;
318
319    fn get_resolve_filter_cache(&mut self) -> Option<&mut ResolveFilterCacheReadTxn<'a>>;
320
321    fn get_feature_hmac_name_history_config(&self) -> &HmacNameHistoryConfig;
322
323    fn get_feature_account_signup_config(&self) -> &AccountSignupConfig;
324
325    fn txn_name_to_uuid(&mut self) -> &mut BTreeMap<String, Uuid>;
326
327    // Because of how borrowck in rust works, if we need to get two inner types we have to get them
328    // in a single fn.
329
330    fn get_resolve_filter_cache_and_be_txn(
331        &mut self,
332    ) -> (
333        &mut Self::BackendTransactionType,
334        Option<&mut ResolveFilterCacheReadTxn<'a>>,
335    );
336
337    /// Conduct a search and apply access controls to yield a set of entries that
338    /// have been reduced to the set of user visible avas. Note that if you provide
339    /// a `SearchEvent` for the internal user, this query will fail. It is invalid for
340    /// the [`access`] module to attempt to reduce avas for internal searches, and you
341    /// should use [`fn search`] instead.
342    ///
343    /// [`SearchEvent`]: ../event/struct.SearchEvent.html
344    /// [`access`]: ../access/index.html
345    /// [`fn search`]: trait.QueryServerTransaction.html#method.search
346    #[instrument(level = "debug", skip_all)]
347    fn search_ext(
348        &mut self,
349        se: &SearchEvent,
350    ) -> Result<Vec<EntryReducedCommitted>, OperationError> {
351        /*
352         * This just wraps search, but it's for the external interface
353         * so as a result it also reduces the entry set's attributes at
354         * the end.
355         */
356        let entries = self.search(se)?;
357
358        let access = self.get_accesscontrols();
359        access
360            .search_filter_entry_attributes(se, entries)
361            .map_err(|e| {
362                // Log and fail if something went wrong.
363                admin_error!(?e, "Failed to filter entry attributes");
364                e
365            })
366        // This now returns the reduced vec.
367    }
368
369    #[instrument(level = "debug", skip_all)]
370    fn search(
371        &mut self,
372        se: &SearchEvent,
373    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
374        if se.ident.is_internal() {
375            trace!(internal_filter = ?se.filter, "search");
376        } else {
377            security_info!(initiator = %se.ident, "search");
378            admin_debug!(external_filter = ?se.filter, "search");
379        }
380
381        // This is an important security step because it prevents us from
382        // performing un-indexed searches on attr's that don't exist in the
383        // server. This is why ExtensibleObject can only take schema that
384        // exists in the server, not arbitrary attr names.
385        //
386        // This normalises and validates in a single step.
387        //
388        // NOTE: Filters are validated in event conversion.
389
390        let (be_txn, resolve_filter_cache) = self.get_resolve_filter_cache_and_be_txn();
391
392        let idxmeta = be_txn.get_idxmeta_ref();
393
394        trace!(resolve_filter_cache = %resolve_filter_cache.is_some());
395
396        // Now resolve all references and indexes.
397        let vfr = se
398            .filter
399            .resolve(&se.ident, Some(idxmeta), resolve_filter_cache)
400            .map_err(|e| {
401                admin_error!(?e, "search filter resolve failure");
402                e
403            })?;
404
405        let lims = se.ident.limits();
406
407        // NOTE: We currently can't build search plugins due to the inability to hand
408        // the QS wr/ro to the plugin trait. However, there shouldn't be a need for search
409        // plugins, because all data transforms should be in the write path.
410
411        let res = self.get_be_txn().search(lims, &vfr).map_err(|e| {
412            admin_error!(?e, "backend failure");
413            OperationError::Backend
414        })?;
415
416        // Apply ACP before we let the plugins "have at it".
417        // WARNING; for external searches this is NOT the only
418        // ACP application. There is a second application to reduce the
419        // attribute set on the entries!
420        //
421        let access = self.get_accesscontrols();
422        access.search_filter_entries(se, res).map_err(|e| {
423            admin_error!(?e, "Unable to access filter entries");
424            e
425        })
426    }
427
428    #[instrument(level = "debug", skip_all)]
429    fn exists(&mut self, ee: &ExistsEvent) -> Result<bool, OperationError> {
430        let (be_txn, resolve_filter_cache) = self.get_resolve_filter_cache_and_be_txn();
431        let idxmeta = be_txn.get_idxmeta_ref();
432
433        let vfr = ee
434            .filter
435            .resolve(&ee.ident, Some(idxmeta), resolve_filter_cache)
436            .map_err(|e| {
437                admin_error!(?e, "Failed to resolve filter");
438                e
439            })?;
440
441        let lims = ee.ident.limits();
442
443        if ee.ident.is_internal() {
444            // We take a fast-path on internal because we can skip loading entries
445            // at all in this case.
446            be_txn.exists(lims, &vfr).map_err(|e| {
447                admin_error!(?e, "backend failure");
448                OperationError::Backend
449            })
450        } else {
451            // For external idents, we need to load the entries else we can't apply
452            // access controls to them.
453            let res = self.get_be_txn().search(lims, &vfr).map_err(|e| {
454                admin_error!(?e, "backend failure");
455                OperationError::Backend
456            })?;
457
458            // ⚠️  Compare / Exists is annoying security wise. It has the
459            // capability to easily leak information based on comparisons
460            // that have been made. In the external account case, we need
461            // to filter entries as a result.
462
463            // Apply ACP before we return the bool state.
464            let access = self.get_accesscontrols();
465            access
466                .filter_entries(&ee.ident, &ee.filter_orig, res)
467                .map_err(|e| {
468                    admin_error!(?e, "Unable to access filter entries");
469                    e
470                })
471                .map(|entries| !entries.is_empty())
472        }
473    }
474
475    fn name_to_uuid(&mut self, name: &str) -> Result<Uuid, OperationError> {
476        // There are some contexts where we will be passed an rdn or dn. We need
477        // to remove these elements if they exist.
478        //
479        // Why is it okay to ignore the attr and dn here? In Kani spn and name are
480        // always unique and absolutes, so even if the dn/rdn are not expected, there
481        // is only a single correct answer that *can* match these values. This also
482        // hugely simplifies the process of matching when we have app based searches
483        // in future too.
484        let work = EXTRACT_VAL_DN
485            .captures(name)
486            .and_then(|caps| caps.name("val"))
487            .map(|v| v.as_str().to_lowercase())
488            .ok_or(OperationError::InvalidValueState)?;
489
490        // Is it just a uuid?
491        if let Ok(uuid) = Uuid::parse_str(&work) {
492            return Ok(uuid);
493        }
494
495        if let Some(uuid) = self.get_be_txn().name2uuid(&work)? {
496            return Ok(uuid);
497        }
498
499        if let Some(uuid) = self.txn_name_to_uuid().get(name) {
500            Ok(*uuid)
501        } else {
502            Err(OperationError::NoMatchingEntries)
503        }
504    }
505
506    // Similar to name, but where we lookup from external_id instead.
507    fn sync_external_id_to_uuid(
508        &mut self,
509        external_id: &str,
510    ) -> Result<Option<Uuid>, OperationError> {
511        // Is it just a uuid?
512        Uuid::parse_str(external_id).map(Some).or_else(|_| {
513            let lname = external_id.to_lowercase();
514            self.get_be_txn().externalid2uuid(lname.as_str())
515        })
516    }
517
518    fn uuid_to_spn(&mut self, uuid: Uuid) -> Result<Option<Value>, OperationError> {
519        let r = self.get_be_txn().uuid2spn(uuid)?;
520
521        if let Some(ref n) = r {
522            // Shouldn't we be doing more graceful error handling here?
523            // Or, if we know it will always be true, we should remove this.
524            debug_assert!(n.is_spn() || n.is_iname());
525        }
526
527        Ok(r)
528    }
529
530    fn uuid_to_rdn(&mut self, uuid: Uuid) -> Result<String, OperationError> {
531        // If we have a some, pass it on, else unwrap into a default.
532        self.get_be_txn()
533            .uuid2rdn(uuid)
534            .map(|v| v.unwrap_or_else(|| format!("uuid={}", uuid.as_hyphenated())))
535    }
536
537    /// From internal, generate an "exists" event and dispatch
538    #[instrument(level = "debug", skip_all)]
539    fn internal_exists(&mut self, filter: &Filter<FilterInvalid>) -> Result<bool, OperationError> {
540        // Check the filter
541        let f_valid = filter
542            .validate(self.get_schema())
543            .map_err(OperationError::SchemaViolation)?;
544        // Build an exists event
545        let ee = ExistsEvent::new_internal(f_valid);
546        // Submit it
547        self.exists(&ee)
548    }
549
550    #[instrument(level = "debug", skip_all)]
551    fn internal_exists_uuid(&mut self, uuid: Uuid) -> Result<bool, OperationError> {
552        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
553        self.internal_exists(&filter)
554    }
555
556    #[instrument(level = "debug", skip_all)]
557    fn internal_search(
558        &mut self,
559        filter: Filter<FilterInvalid>,
560    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
561        let f_valid = filter
562            .validate(self.get_schema())
563            .map_err(OperationError::SchemaViolation)?;
564        let se = SearchEvent::new_internal(f_valid);
565        self.search(&se)
566    }
567
568    #[instrument(level = "debug", skip_all)]
569    fn impersonate_search_valid(
570        &mut self,
571        f_valid: Filter<FilterValid>,
572        f_intent_valid: Filter<FilterValid>,
573        event: &Identity,
574    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
575        let se = SearchEvent::new_impersonate(event, f_valid, f_intent_valid);
576        self.search(&se)
577    }
578
579    /// Applies ACP to filter result entries.
580    fn impersonate_search_ext_valid(
581        &mut self,
582        f_valid: Filter<FilterValid>,
583        f_intent_valid: Filter<FilterValid>,
584        event: &Identity,
585    ) -> Result<Vec<Entry<EntryReduced, EntryCommitted>>, OperationError> {
586        let se = SearchEvent::new_impersonate(event, f_valid, f_intent_valid);
587        self.search_ext(&se)
588    }
589
590    fn ident_search(
591        &mut self,
592        ident: &Identity,
593        filter: Filter<FilterInvalid>,
594    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
595        let f_intent_valid = filter
596            .validate(self.get_schema())
597            .map_err(OperationError::SchemaViolation)?;
598
599        let f_valid = f_intent_valid.clone().into_ignore_hidden();
600
601        let se = SearchEvent::new_impersonate(ident, f_valid, f_intent_valid);
602        self.search(&se)
603    }
604
605    fn ident_search_single(
606        &mut self,
607        ident: &Identity,
608        filter: Filter<FilterInvalid>,
609    ) -> Result<Arc<EntrySealedCommitted>, OperationError> {
610        let mut vs = self.ident_search(ident, filter)?;
611        match vs.pop() {
612            Some(entry) if vs.is_empty() => Ok(entry),
613            _ => Err(OperationError::NoMatchingEntries),
614        }
615    }
616
617    // Who they are will go here
618    fn impersonate_search(
619        &mut self,
620        filter: Filter<FilterInvalid>,
621        filter_intent: Filter<FilterInvalid>,
622        event: &Identity,
623    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
624        let f_valid = filter
625            .validate(self.get_schema())
626            .map_err(OperationError::SchemaViolation)?;
627        let f_intent_valid = filter_intent
628            .validate(self.get_schema())
629            .map_err(OperationError::SchemaViolation)?;
630        self.impersonate_search_valid(f_valid, f_intent_valid, event)
631    }
632
633    #[instrument(level = "debug", skip_all)]
634    fn impersonate_search_ext(
635        &mut self,
636        filter: Filter<FilterInvalid>,
637        filter_intent: Filter<FilterInvalid>,
638        event: &Identity,
639    ) -> Result<Vec<Entry<EntryReduced, EntryCommitted>>, OperationError> {
640        let f_valid = filter
641            .validate(self.get_schema())
642            .map_err(OperationError::SchemaViolation)?;
643        let f_intent_valid = filter_intent
644            .validate(self.get_schema())
645            .map_err(OperationError::SchemaViolation)?;
646        self.impersonate_search_ext_valid(f_valid, f_intent_valid, event)
647    }
648
649    /// Get a single entry by its UUID. This is used heavily for internal
650    /// server operations, especially in login and ACP checks.
651    #[instrument(level = "debug", skip_all)]
652    fn internal_search_uuid(
653        &mut self,
654        uuid: Uuid,
655    ) -> Result<Arc<EntrySealedCommitted>, OperationError> {
656        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
657        let f_valid = filter.validate(self.get_schema()).map_err(|e| {
658            error!(?e, "Filter Validate - SchemaViolation");
659            OperationError::SchemaViolation(e)
660        })?;
661        let se = SearchEvent::new_internal(f_valid);
662
663        let mut vs = self.search(&se)?;
664        match vs.pop() {
665            Some(entry) if vs.is_empty() => Ok(entry),
666            _ => Err(OperationError::NoMatchingEntries),
667        }
668    }
669
670    /// Get a single entry by its UUID, even if the entry in question
671    /// is in a masked state (recycled, tombstoned).
672    #[instrument(level = "debug", skip_all)]
673    fn internal_search_all_uuid(
674        &mut self,
675        uuid: Uuid,
676    ) -> Result<Arc<EntrySealedCommitted>, OperationError> {
677        let filter = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
678        let f_valid = filter.validate(self.get_schema()).map_err(|e| {
679            error!(?e, "Filter Validate - SchemaViolation");
680            OperationError::SchemaViolation(e)
681        })?;
682        let se = SearchEvent::new_internal(f_valid);
683
684        let mut vs = self.search(&se)?;
685        match vs.pop() {
686            Some(entry) if vs.is_empty() => Ok(entry),
687            _ => Err(OperationError::NoMatchingEntries),
688        }
689    }
690
691    /// Get all conflict entries that originated from a source uuid.
692    #[instrument(level = "debug", skip_all)]
693    fn internal_search_conflict_uuid(
694        &mut self,
695        uuid: Uuid,
696    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
697        let filter = filter_all!(f_and(vec![
698            f_eq(Attribute::SourceUuid, PartialValue::Uuid(uuid)),
699            f_eq(Attribute::Class, EntryClass::Conflict.into())
700        ]));
701        let f_valid = filter.validate(self.get_schema()).map_err(|e| {
702            error!(?e, "Filter Validate - SchemaViolation");
703            OperationError::SchemaViolation(e)
704        })?;
705        let se = SearchEvent::new_internal(f_valid);
706
707        self.search(&se)
708    }
709
710    #[instrument(level = "debug", skip_all)]
711    fn impersonate_search_ext_uuid(
712        &mut self,
713        uuid: Uuid,
714        event: &Identity,
715    ) -> Result<Entry<EntryReduced, EntryCommitted>, OperationError> {
716        let filter_intent = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
717        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
718
719        let mut vs = self.impersonate_search_ext(filter, filter_intent, event)?;
720        match vs.pop() {
721            Some(entry) if vs.is_empty() => Ok(entry),
722            _ => {
723                if vs.is_empty() {
724                    Err(OperationError::NoMatchingEntries)
725                } else {
726                    // Multiple entries matched, should not be possible!
727                    Err(OperationError::UniqueConstraintViolation)
728                }
729            }
730        }
731    }
732
733    #[instrument(level = "debug", skip_all)]
734    fn impersonate_search_uuid(
735        &mut self,
736        uuid: Uuid,
737        event: &Identity,
738    ) -> Result<Arc<EntrySealedCommitted>, OperationError> {
739        let filter_intent = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
740        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)));
741
742        let mut vs = self.impersonate_search(filter, filter_intent, event)?;
743        match vs.pop() {
744            Some(entry) if vs.is_empty() => Ok(entry),
745            _ => Err(OperationError::NoMatchingEntries),
746        }
747    }
748
749    /// Given an entries UUID, return an impersonation session for that account. This
750    /// should be used with care, as it allows you to perform actions internally on
751    /// behalf of a another user, without checking the permissions of the original
752    /// user.
753    fn impersonate_uuid_as_readwrite_identity(
754        &mut self,
755        uuid: Uuid,
756    ) -> Result<Identity, OperationError> {
757        self.internal_search_uuid(uuid)
758            .map(Identity::from_impersonate_entry_readwrite)
759    }
760
761    /// Do a schema aware conversion from a String:String to String:Value for modification
762    /// present.
763    fn clone_value(&mut self, attr: &Attribute, value: &str) -> Result<Value, OperationError> {
764        let schema = self.get_schema();
765
766        // Should this actually be a fn of Value - no - I think that introduces issues with the
767        // monomorphisation of the trait for transactions, so we should have this here.
768
769        // Lookup the attr
770        match schema.get_attributes().get(attr) {
771            Some(schema_a) => {
772                match schema_a.syntax {
773                    SyntaxType::Utf8String => Ok(Value::new_utf8(value.to_string())),
774                    SyntaxType::Utf8StringInsensitiveN => Ok(Value::new_iutf8n(value)),
775                    SyntaxType::Utf8StringInsensitive => Ok(Value::new_iutf8(value)),
776                    SyntaxType::Utf8StringInameN => Ok(Value::new_inamen(value)),
777                    SyntaxType::Utf8StringIname => Ok(Value::new_iname(value)),
778                    SyntaxType::Boolean => Value::new_bools(value)
779                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid boolean syntax".to_string())),
780                    SyntaxType::SyntaxId => Value::new_syntaxs(value)
781                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Syntax syntax".to_string())),
782                    SyntaxType::IndexId => Value::new_indexes(value)
783                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Index syntax".to_string())),
784                    SyntaxType::CredentialType => CredentialType::try_from(value)
785                        .map(Value::CredentialType)
786                        .map_err(|()| OperationError::InvalidAttribute("Invalid CredentialType syntax".to_string())),
787                    SyntaxType::Uuid => {
788                        // Attempt to resolve this name to a uuid. If it's already a uuid, then
789                        // name to uuid will "do the right thing" and give us the Uuid back.
790                        let un = self
791                            .name_to_uuid(value)
792                            .unwrap_or(UUID_DOES_NOT_EXIST);
793                        Ok(Value::Uuid(un))
794                    }
795                    SyntaxType::ReferenceUuidN
796                    => {
797                        let un = self
798                            .name_to_uuid(value)
799                            .unwrap_or(UUID_DOES_NOT_EXIST);
800                        Ok(Value::ReferN(un))
801                    }
802                    SyntaxType::ReferenceUuid
803                    => {
804                        let un = self
805                            .name_to_uuid(value)
806                            .unwrap_or(UUID_DOES_NOT_EXIST);
807                        Ok(Value::Refer(un))
808                    }
809                    SyntaxType::JsonFilter => Value::new_json_filter_s(value)
810                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Filter syntax".to_string())),
811                    SyntaxType::Image => Value::new_image(value),
812
813                    SyntaxType::Credential => Err(OperationError::InvalidAttribute("Credentials can not be supplied through modification - please use the IDM api".to_string())),
814                    SyntaxType::SecretUtf8String => Err(OperationError::InvalidAttribute("Radius secrets can not be supplied through modification - please use the IDM api".to_string())),
815                    SyntaxType::SshKey => Err(OperationError::InvalidAttribute("SSH public keys can not be supplied through modification - please use the IDM api".to_string())),
816                    SyntaxType::SecurityPrincipalName => Err(OperationError::InvalidAttribute("SPNs are generated and not able to be set.".to_string())),
817                    SyntaxType::Uint32 => Value::new_uint32_str(value)
818                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid uint32 syntax".to_string())),
819                    SyntaxType::Int64 => Value::new_int64_str(value)
820                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid int64 syntax".to_string())),
821                    SyntaxType::Uint64 => Value::new_uint64_str(value)
822                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid uint64 syntax".to_string())),
823                    SyntaxType::Cid => Err(OperationError::InvalidAttribute("CIDs are generated and not able to be set.".to_string())),
824                    SyntaxType::NsUniqueId => Value::new_nsuniqueid_s(value)
825                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid NsUniqueId syntax".to_string())),
826                    SyntaxType::DateTime => Value::new_datetime_s(value)
827                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid DateTime (rfc3339) syntax".to_string())),
828                    SyntaxType::EmailAddress => Value::new_email_address_s(value)
829                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Email Address syntax".to_string())),
830
831                    SyntaxType::UrlN => Value::new_urln_s(value)
832                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Url (whatwg/url) syntax".to_string())),
833                    SyntaxType::Url => Value::new_url_s(value)
834                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Url (whatwg/url) syntax".to_string())),
835                    SyntaxType::OauthScope => Value::new_oauthscope(value)
836                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Oauth Scope syntax".to_string())),
837                    SyntaxType::WebauthnAttestationCaList => Value::new_webauthn_attestation_ca_list(value)
838                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid Webauthn Attestation CA List".to_string())),
839                    SyntaxType::OauthScopeMap => Err(OperationError::InvalidAttribute("Oauth Scope Maps can not be supplied through modification - please use the IDM api".to_string())),
840                    SyntaxType::OauthClaimMap => Err(OperationError::InvalidAttribute("Oauth Claim Maps can not be supplied through modification - please use the IDM api".to_string())),
841                    SyntaxType::PrivateBinary => Err(OperationError::InvalidAttribute("Private Binary Values can not be supplied through modification".to_string())),
842                    SyntaxType::IntentToken => Err(OperationError::InvalidAttribute("Intent Token Values can not be supplied through modification".to_string())),
843                    SyntaxType::Passkey => Err(OperationError::InvalidAttribute("Passkey Values can not be supplied through modification".to_string())),
844                    SyntaxType::AttestedPasskey => Err(OperationError::InvalidAttribute("AttestedPasskey Values can not be supplied through modification".to_string())),
845                    SyntaxType::Session => Err(OperationError::InvalidAttribute("Session Values can not be supplied through modification".to_string())),
846                    SyntaxType::ApiToken => Err(OperationError::InvalidAttribute("ApiToken Values can not be supplied through modification".to_string())),
847                    SyntaxType::JwsKeyEs256 => Err(OperationError::InvalidAttribute("JwsKeyEs256 Values can not be supplied through modification".to_string())),
848                    SyntaxType::JwsKeyRs256 => Err(OperationError::InvalidAttribute("JwsKeyRs256 Values can not be supplied through modification".to_string())),
849                    SyntaxType::Oauth2Session => Err(OperationError::InvalidAttribute("Oauth2Session Values can not be supplied through modification".to_string())),
850                    SyntaxType::UiHint => UiHint::from_str(value)
851                        .map(Value::UiHint)
852                        .map_err(|()| OperationError::InvalidAttribute("Invalid uihint syntax".to_string())),
853                    SyntaxType::TotpSecret => Err(OperationError::InvalidAttribute("TotpSecret Values can not be supplied through modification".to_string())),
854                    SyntaxType::AuditLogString => Err(OperationError::InvalidAttribute("Audit logs are generated and not able to be set.".to_string())),
855                    SyntaxType::EcKeyPrivate => Err(OperationError::InvalidAttribute("Ec keys are generated and not able to be set.".to_string())),
856                    SyntaxType::KeyInternal => Err(OperationError::InvalidAttribute("Internal keys are generated and not able to be set.".to_string())),
857                    SyntaxType::HexString => Value::new_hex_string_s(value)
858                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid hex string syntax".to_string())),
859                    SyntaxType::Certificate => Value::new_certificate_s(value)
860                        .ok_or_else(|| OperationError::InvalidAttribute("Invalid x509 certificate syntax".to_string())),
861                    SyntaxType::ApplicationPassword => Err(OperationError::InvalidAttribute("ApplicationPassword values can not be supplied through modification".to_string())),
862                    SyntaxType::Json => Err(OperationError::InvalidAttribute("Json values can not be supplied through modification".to_string())),
863                    SyntaxType::Sha256 => Err(OperationError::InvalidAttribute("SHA256 values can not be supplied through modification".to_string())),
864                    SyntaxType::Message => Err(OperationError::InvalidAttribute("Message values can not be supplied through modification".to_string())),
865                    SyntaxType::UuidN => Err(OperationError::InvalidAttribute("Uuid-Set values can not be supplied through modification".to_string())),
866                }
867            }
868            None => {
869                // No attribute of this name exists - fail fast, there is no point to
870                // proceed, as nothing can be satisfied.
871                Err(OperationError::InvalidAttributeName(attr.to_string()))
872            }
873        }
874    }
875
876    fn clone_partialvalue(
877        &mut self,
878        attr: &Attribute,
879        value: &str,
880    ) -> Result<PartialValue, OperationError> {
881        let schema = self.get_schema();
882
883        // Lookup the attr
884        match schema.get_attributes().get(attr) {
885            Some(schema_a) => {
886                match schema_a.syntax {
887                    SyntaxType::Utf8String | SyntaxType::TotpSecret => {
888                        Ok(PartialValue::new_utf8(value.to_string()))
889                    }
890                    SyntaxType::Utf8StringInsensitive
891                    | SyntaxType::Utf8StringInsensitiveN
892                    | SyntaxType::JwsKeyEs256
893                    | SyntaxType::JwsKeyRs256 => Ok(PartialValue::new_iutf8(value)),
894                    SyntaxType::Utf8StringInameN | SyntaxType::Utf8StringIname => {
895                        Ok(PartialValue::new_iname(value))
896                    }
897                    SyntaxType::Boolean => PartialValue::new_bools(value).ok_or_else(|| {
898                        OperationError::InvalidAttribute("Invalid boolean syntax".to_string())
899                    }),
900                    SyntaxType::SyntaxId => PartialValue::new_syntaxs(value).ok_or_else(|| {
901                        OperationError::InvalidAttribute("Invalid Syntax syntax".to_string())
902                    }),
903                    SyntaxType::IndexId => PartialValue::new_indexes(value).ok_or_else(|| {
904                        OperationError::InvalidAttribute("Invalid Index syntax".to_string())
905                    }),
906                    SyntaxType::CredentialType => CredentialType::try_from(value)
907                        .map(PartialValue::CredentialType)
908                        .map_err(|()| {
909                            OperationError::InvalidAttribute(
910                                "Invalid credentialtype syntax".to_string(),
911                            )
912                        }),
913                    SyntaxType::Uuid | SyntaxType::UuidN => {
914                        let un = self.name_to_uuid(value).unwrap_or(UUID_DOES_NOT_EXIST);
915                        Ok(PartialValue::Uuid(un))
916                    }
917                    // ⚠️   Any types here need to also be added to update_attributes in
918                    // schema.rs for reference type / cache awareness during referential
919                    // integrity processing. Exceptions are self-contained value types!
920                    SyntaxType::ReferenceUuid
921                    | SyntaxType::ReferenceUuidN
922                    | SyntaxType::OauthScopeMap
923                    | SyntaxType::Session
924                    | SyntaxType::ApiToken
925                    | SyntaxType::Oauth2Session
926                    | SyntaxType::ApplicationPassword => {
927                        let un = self.name_to_uuid(value).unwrap_or(UUID_DOES_NOT_EXIST);
928                        Ok(PartialValue::Refer(un))
929                    }
930                    SyntaxType::OauthClaimMap => self
931                        .name_to_uuid(value)
932                        .map(PartialValue::Refer)
933                        .or_else(|_| Ok(PartialValue::new_iutf8(value))),
934
935                    SyntaxType::JsonFilter => {
936                        PartialValue::new_json_filter_s(value).ok_or_else(|| {
937                            OperationError::InvalidAttribute("Invalid Filter syntax".to_string())
938                        })
939                    }
940                    SyntaxType::Credential => Ok(PartialValue::new_credential_tag(value)),
941                    SyntaxType::SecretUtf8String => Ok(PartialValue::new_secret_str()),
942                    SyntaxType::SshKey => Ok(PartialValue::new_sshkey_tag_s(value)),
943                    SyntaxType::SecurityPrincipalName => {
944                        PartialValue::new_spn_s(value).ok_or_else(|| {
945                            OperationError::InvalidAttribute("Invalid spn syntax".to_string())
946                        })
947                    }
948                    SyntaxType::Uint32 => PartialValue::new_uint32_str(value).ok_or_else(|| {
949                        OperationError::InvalidAttribute("Invalid uint32 syntax".to_string())
950                    }),
951                    SyntaxType::Uint64 => PartialValue::new_uint64_str(value).ok_or_else(|| {
952                        OperationError::InvalidAttribute("Invalid uint64 syntax".to_string())
953                    }),
954                    SyntaxType::Int64 => PartialValue::new_int64_str(value).ok_or_else(|| {
955                        OperationError::InvalidAttribute("Invalid int64 syntax".to_string())
956                    }),
957                    SyntaxType::Cid => PartialValue::new_cid_s(value).ok_or_else(|| {
958                        OperationError::InvalidAttribute("Invalid cid syntax".to_string())
959                    }),
960                    SyntaxType::NsUniqueId => Ok(PartialValue::new_nsuniqueid_s(value)),
961                    SyntaxType::DateTime => PartialValue::new_datetime_s(value).ok_or_else(|| {
962                        OperationError::InvalidAttribute(
963                            "Invalid DateTime (rfc3339) syntax".to_string(),
964                        )
965                    }),
966                    SyntaxType::EmailAddress => Ok(PartialValue::new_email_address_s(value)),
967                    SyntaxType::UrlN | SyntaxType::Url => PartialValue::new_url_s(value)
968                        .ok_or_else(|| {
969                            OperationError::InvalidAttribute(
970                                "Invalid Url (whatwg/url) syntax".to_string(),
971                            )
972                        }),
973                    SyntaxType::OauthScope => Ok(PartialValue::new_oauthscope(value)),
974                    SyntaxType::PrivateBinary => Ok(PartialValue::PrivateBinary),
975                    SyntaxType::IntentToken => PartialValue::new_intenttoken_s(value.to_string())
976                        .ok_or_else(|| {
977                            OperationError::InvalidAttribute(
978                                "Invalid Intent Token ID (uuid) syntax".to_string(),
979                            )
980                        }),
981                    SyntaxType::Passkey => PartialValue::new_passkey_s(value).ok_or_else(|| {
982                        OperationError::InvalidAttribute("Invalid Passkey UUID syntax".to_string())
983                    }),
984                    SyntaxType::AttestedPasskey => PartialValue::new_attested_passkey_s(value)
985                        .ok_or_else(|| {
986                            OperationError::InvalidAttribute(
987                                "Invalid AttestedPasskey UUID syntax".to_string(),
988                            )
989                        }),
990                    SyntaxType::UiHint => UiHint::from_str(value)
991                        .map(PartialValue::UiHint)
992                        .map_err(|()| {
993                            OperationError::InvalidAttribute("Invalid uihint syntax".to_string())
994                        }),
995                    SyntaxType::AuditLogString => Ok(PartialValue::new_utf8s(value)),
996                    SyntaxType::EcKeyPrivate => Ok(PartialValue::SecretValue),
997                    SyntaxType::Image => Ok(PartialValue::new_utf8s(value)),
998                    SyntaxType::WebauthnAttestationCaList => Err(OperationError::InvalidAttribute(
999                        "Invalid - unable to query attestation CA list".to_string(),
1000                    )),
1001                    SyntaxType::HexString | SyntaxType::KeyInternal | SyntaxType::Certificate => {
1002                        PartialValue::new_hex_string_s(value).ok_or_else(|| {
1003                            OperationError::InvalidAttribute(
1004                                "Invalid syntax, expected hex string".to_string(),
1005                            )
1006                        })
1007                    }
1008                    SyntaxType::Sha256 => {
1009                        let mut sha256bytes = Sha256Output::default();
1010                        if hex::decode_to_slice(value, &mut sha256bytes).is_ok() {
1011                            Ok(PartialValue::Sha256(sha256bytes))
1012                        } else {
1013                            Err(OperationError::InvalidAttribute(
1014                                "Invalid syntax, expected sha256 hex string containing 64 characters".to_string(),
1015                            ))
1016                        }
1017                    }
1018                    SyntaxType::Json => Err(OperationError::InvalidAttribute(
1019                        "Json values can not be validated by this interface".to_string(),
1020                    )),
1021                    SyntaxType::Message => Err(OperationError::InvalidAttribute(
1022                        "Message values can not be validated by this interface".to_string(),
1023                    )),
1024                }
1025            }
1026            None => {
1027                // No attribute of this name exists - fail fast, there is no point to
1028                // proceed, as nothing can be satisfied.
1029                Err(OperationError::InvalidAttributeName(attr.to_string()))
1030            }
1031        }
1032    }
1033
1034    fn resolve_scim_interim(
1035        &mut self,
1036        scim_value_intermediate: ScimValueIntermediate,
1037    ) -> Result<Option<ScimValueKanidm>, OperationError> {
1038        match scim_value_intermediate {
1039            ScimValueIntermediate::Reference(uuid) => {
1040                let scim_reference = self
1041                    .uuid_to_spn(uuid)
1042                    .and_then(|maybe_value| maybe_value.ok_or(OperationError::InvalidValueState))
1043                    .map(|value| ScimReference {
1044                        uuid,
1045                        value: value.to_proto_string_clone(),
1046                    })?;
1047                Ok(Some(ScimValueKanidm::EntryReference(scim_reference)))
1048            }
1049
1050            ScimValueIntermediate::References(uuids) => {
1051                let scim_references = uuids
1052                    .into_iter()
1053                    .map(|uuid| {
1054                        self.uuid_to_spn(uuid)
1055                            .and_then(|maybe_value| {
1056                                maybe_value.ok_or(OperationError::InvalidValueState)
1057                            })
1058                            .map(|value| ScimReference {
1059                                uuid,
1060                                value: value.to_proto_string_clone(),
1061                            })
1062                    })
1063                    .collect::<Result<Vec<_>, _>>()?;
1064                Ok(Some(ScimValueKanidm::EntryReferences(scim_references)))
1065            }
1066            ScimValueIntermediate::Oauth2ClaimMap(unresolved_maps) => {
1067                let scim_claim_maps = unresolved_maps
1068                    .into_iter()
1069                    .map(
1070                        |UnresolvedScimValueOauth2ClaimMap {
1071                             group_uuid,
1072                             claim,
1073                             join_char,
1074                             values,
1075                         }| {
1076                            self.uuid_to_spn(group_uuid)
1077                                .and_then(|maybe_value| {
1078                                    maybe_value.ok_or(OperationError::InvalidValueState)
1079                                })
1080                                .map(|value| ScimOAuth2ClaimMap {
1081                                    group: value.to_proto_string_clone(),
1082                                    group_uuid,
1083                                    claim,
1084                                    join_char,
1085                                    values,
1086                                })
1087                        },
1088                    )
1089                    .collect::<Result<Vec<_>, _>>()?;
1090
1091                Ok(Some(ScimValueKanidm::OAuth2ClaimMap(scim_claim_maps)))
1092            }
1093
1094            ScimValueIntermediate::Oauth2ScopeMap(unresolved_maps) => {
1095                let scim_claim_maps = unresolved_maps
1096                    .into_iter()
1097                    .map(|UnresolvedScimValueOauth2ScopeMap { group_uuid, scopes }| {
1098                        self.uuid_to_spn(group_uuid)
1099                            .and_then(|maybe_value| {
1100                                maybe_value.ok_or(OperationError::InvalidValueState)
1101                            })
1102                            .map(|value| ScimOAuth2ScopeMap {
1103                                group: value.to_proto_string_clone(),
1104                                group_uuid,
1105                                scopes,
1106                            })
1107                    })
1108                    .collect::<Result<Vec<_>, _>>()?;
1109
1110                Ok(Some(ScimValueKanidm::OAuth2ScopeMap(scim_claim_maps)))
1111            }
1112        }
1113    }
1114
1115    fn resolve_scim_json_get(
1116        &mut self,
1117        attr: &Attribute,
1118        value: &JsonValue,
1119    ) -> Result<PartialValue, OperationError> {
1120        let schema = self.get_schema();
1121        // Lookup the attr
1122        let Some(schema_a) = schema.get_attributes().get(attr) else {
1123            // No attribute of this name exists - fail fast, there is no point to
1124            // proceed, as nothing can be satisfied.
1125            return Err(OperationError::InvalidAttributeName(attr.to_string()));
1126        };
1127
1128        debug!(schema_syntax = ?schema_a.syntax, ?value);
1129
1130        match schema_a.syntax {
1131            SyntaxType::Utf8String => {
1132                let JsonValue::String(value) = value else {
1133                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1134                };
1135                Ok(PartialValue::Utf8(value.to_string()))
1136            }
1137            SyntaxType::Utf8StringInsensitive | SyntaxType::Utf8StringInsensitiveN => {
1138                let JsonValue::String(value) = value else {
1139                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1140                };
1141                Ok(PartialValue::new_iutf8(value))
1142            }
1143            SyntaxType::Utf8StringIname | SyntaxType::Utf8StringInameN => {
1144                let JsonValue::String(value) = value else {
1145                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1146                };
1147                Ok(PartialValue::new_iname(value))
1148            }
1149            SyntaxType::Uuid | SyntaxType::UuidN => {
1150                let JsonValue::String(value) = value else {
1151                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1152                };
1153
1154                let un = self.name_to_uuid(value).unwrap_or(UUID_DOES_NOT_EXIST);
1155                Ok(PartialValue::Uuid(un))
1156            }
1157            SyntaxType::Boolean => {
1158                let JsonValue::Bool(value) = value else {
1159                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1160                };
1161                Ok(PartialValue::Bool(*value))
1162            }
1163            SyntaxType::SyntaxId => {
1164                let JsonValue::String(value) = value else {
1165                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1166                };
1167                let Ok(value) = SyntaxType::try_from(value.as_str()) else {
1168                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1169                };
1170                Ok(PartialValue::Syntax(value))
1171            }
1172            SyntaxType::ReferenceUuid
1173            | SyntaxType::ReferenceUuidN
1174            | SyntaxType::OauthScopeMap
1175            | SyntaxType::Session
1176            | SyntaxType::ApiToken
1177            | SyntaxType::Oauth2Session
1178            | SyntaxType::ApplicationPassword => {
1179                let JsonValue::String(value) = value else {
1180                    return Err(OperationError::InvalidAttribute(attr.to_string()));
1181                };
1182
1183                let un = self.name_to_uuid(value).unwrap_or(UUID_DOES_NOT_EXIST);
1184                Ok(PartialValue::Refer(un))
1185            }
1186
1187            syntax => {
1188                debug!(?attr, ?syntax, "resolve_scim_json_get not implemented");
1189                Err(OperationError::InvalidAttribute(attr.to_string()))
1190            }
1191        }
1192    }
1193
1194    fn resolve_valueset_intermediate(
1195        &mut self,
1196        vs_inter: ValueSetIntermediate,
1197    ) -> Result<ValueSet, OperationError> {
1198        match vs_inter {
1199            ValueSetIntermediate::Reference(reference) => {
1200                let resolved = match reference {
1201                            UnresolvedReferenceState::Uuid(uuid) => uuid,
1202                            UnresolvedReferenceState::Value(value) => {
1203                                self.name_to_uuid(value.as_str()).unwrap_or_else(|_| {
1204                                    warn!(
1205                                        ?value,
1206                                        "Value can not be resolved to a uuid - assuming it does not exist."
1207                                    );
1208                                    UUID_DOES_NOT_EXIST
1209                                })
1210                            }
1211                            UnresolvedReferenceState::Complete {
1212                                uuid, value
1213                            } => {
1214                                self.name_to_uuid(value.as_str())
1215                                    .inspect(|r_uuid| if *r_uuid != uuid {
1216                                        warn!(?r_uuid, ?uuid, "Resolved uuid does not match provided uuid for value - this will become an error in future.");
1217                                    })
1218                                .unwrap_or_else(|_| {
1219                                    warn!(
1220                                        ?value,
1221                                        "Value can not be resolved to a uuid - assuming it does not exist."
1222                                    );
1223                                    uuid
1224                                })
1225                            }
1226                        };
1227
1228                let vs = ValueSetRefer::new(resolved);
1229                Ok(vs)
1230            }
1231
1232            ValueSetIntermediate::References { unresolved } => {
1233                let resolved = unresolved.into_iter()
1234                    .map(|value| {
1235
1236                        match value {
1237                            UnresolvedReferenceState::Uuid(uuid) => uuid,
1238                            UnresolvedReferenceState::Value(value) => {
1239                                self.name_to_uuid(value.as_str()).unwrap_or_else(|_| {
1240                                    warn!(
1241                                        ?value,
1242                                        "Value can not be resolved to a uuid - assuming it does not exist."
1243                                    );
1244                                    UUID_DOES_NOT_EXIST
1245                                })
1246                            }
1247                            UnresolvedReferenceState::Complete {
1248                                uuid, value
1249                            } => {
1250                                self.name_to_uuid(value.as_str())
1251                                    .inspect(|r_uuid| if *r_uuid != uuid {
1252                                        warn!(?r_uuid, ?uuid, "Resolved uuid does not match provided uuid for value - this will become an error in future.");
1253                                    })
1254                                .unwrap_or_else(|_| {
1255                                    warn!(
1256                                        ?value,
1257                                        "Value can not be resolved to a uuid - assuming it does not exist."
1258                                    );
1259                                    uuid
1260                                })
1261                            }
1262                        }
1263                    })
1264                    .collect();
1265
1266                let vs = ValueSetReferN::from_set(resolved);
1267                Ok(vs)
1268            }
1269
1270            ValueSetIntermediate::Oauth2ClaimMap {
1271                mut resolved,
1272                unresolved,
1273            } => {
1274                resolved.extend(unresolved.into_iter().map(
1275                    |UnresolvedValueSetOauth2ClaimMap {
1276                         group_name,
1277                         claim,
1278                         join_char,
1279                         claim_values,
1280                     }| {
1281                        let group_uuid =
1282                            self.name_to_uuid(group_name.as_str()).unwrap_or_else(|_| {
1283                                warn!(
1284                            ?group_name,
1285                            "Value can not be resolved to a uuid - assuming it does not exist."
1286                        );
1287                                UUID_DOES_NOT_EXIST
1288                            });
1289
1290                        ResolvedValueSetOauth2ClaimMap {
1291                            group_uuid,
1292                            claim,
1293                            join_char,
1294                            claim_values,
1295                        }
1296                    },
1297                ));
1298
1299                let vs = ValueSetOauthClaimMap::from_set(resolved);
1300                Ok(vs)
1301            }
1302
1303            ValueSetIntermediate::Oauth2ScopeMap {
1304                mut resolved,
1305                unresolved,
1306            } => {
1307                resolved.extend(unresolved.into_iter().map(
1308                    |UnresolvedValueSetOauth2ScopeMap { group_name, scopes }| {
1309                        let group_uuid =
1310                            self.name_to_uuid(group_name.as_str()).unwrap_or_else(|_| {
1311                                warn!(
1312                            ?group_name,
1313                            "Value can not be resolved to a uuid - assuming it does not exist."
1314                        );
1315                                UUID_DOES_NOT_EXIST
1316                            });
1317
1318                        ResolvedValueSetOauth2ScopeMap { group_uuid, scopes }
1319                    },
1320                ));
1321
1322                let vs = ValueSetOauthScopeMap::from_set(resolved);
1323                Ok(vs)
1324            }
1325        }
1326    }
1327
1328    // In the opposite direction, we can resolve values for presentation
1329    fn resolve_valueset(&mut self, value: &ValueSet) -> Result<Vec<String>, OperationError> {
1330        if let Some(r_set) = value.as_refer_set() {
1331            let v: Result<Vec<_>, _> = r_set
1332                .iter()
1333                .copied()
1334                .map(|ur| {
1335                    let nv = self.uuid_to_spn(ur)?;
1336                    match nv {
1337                        Some(v) => Ok(v.to_proto_string_clone()),
1338                        None => Ok(uuid_to_proto_string(ur)),
1339                    }
1340                })
1341                .collect();
1342            v
1343        } else if let Some(r_map) = value.as_oauthscopemap() {
1344            let v: Result<Vec<_>, _> = r_map
1345                .iter()
1346                .map(|(u, m)| {
1347                    let nv = self.uuid_to_spn(*u)?;
1348                    let u = match nv {
1349                        Some(v) => v.to_proto_string_clone(),
1350                        None => uuid_to_proto_string(*u),
1351                    };
1352                    Ok(format!("{u}: {m:?}"))
1353                })
1354                .collect();
1355            v
1356        } else if let Some(r_map) = value.as_oauthclaim_map() {
1357            let mut v = Vec::with_capacity(0);
1358            for (claim_name, mapping) in r_map.iter() {
1359                for (group_ref, claims) in mapping.values() {
1360                    let join_char = mapping.join().to_str();
1361
1362                    let nv = self.uuid_to_spn(*group_ref)?;
1363                    let resolved_id = match nv {
1364                        Some(v) => v.to_proto_string_clone(),
1365                        None => uuid_to_proto_string(*group_ref),
1366                    };
1367
1368                    let joined = str_concat!(claims, ",");
1369
1370                    v.push(format!("{claim_name}:{resolved_id}:{join_char}:{joined:?}"))
1371                }
1372            }
1373            Ok(v)
1374        } else {
1375            let v: Vec<_> = value.to_proto_string_clone_iter().collect();
1376            Ok(v)
1377        }
1378    }
1379
1380    fn resolve_valueset_ldap(
1381        &mut self,
1382        value: &ValueSet,
1383        basedn: &str,
1384    ) -> Result<Vec<Vec<u8>>, OperationError> {
1385        if let Some(r_set) = value.as_refer_set() {
1386            let v: Result<Vec<_>, _> = r_set
1387                .iter()
1388                .copied()
1389                .map(|ur| {
1390                    let rdn = self.uuid_to_rdn(ur)?;
1391                    Ok(format!("{rdn},{basedn}").into_bytes())
1392                })
1393                .collect();
1394            v
1395        // We have to special case ssh keys here as the proto form isn't valid for
1396        // sss_ssh_authorized_keys to consume.
1397        } else if let Some(key_iter) = value.as_sshpubkey_string_iter() {
1398            let v: Vec<_> = key_iter.map(|s| s.into_bytes()).collect();
1399            Ok(v)
1400        } else {
1401            let v: Vec<_> = value
1402                .to_proto_string_clone_iter()
1403                .map(|s| s.into_bytes())
1404                .collect();
1405            Ok(v)
1406        }
1407    }
1408
1409    fn get_db_domain(&mut self) -> Result<Arc<EntrySealedCommitted>, OperationError> {
1410        self.internal_search_uuid(UUID_DOMAIN_INFO)
1411    }
1412
1413    fn get_domain_key_object_handle(&self) -> Result<Arc<KeyObject>, OperationError> {
1414        self.get_key_providers()
1415            .get_key_object_handle(UUID_DOMAIN_INFO)
1416            .ok_or(OperationError::KP0031KeyObjectNotFound)
1417    }
1418
1419    fn get_domain_es256_private_key(&mut self) -> Result<Vec<u8>, OperationError> {
1420        self.internal_search_uuid(UUID_DOMAIN_INFO)
1421            .and_then(|e| {
1422                e.get_ava_single_private_binary(Attribute::Es256PrivateKeyDer)
1423                    .map(|s| s.to_vec())
1424                    .ok_or(OperationError::InvalidEntryState)
1425            })
1426            .map_err(|e| {
1427                admin_error!(?e, "Error getting domain es256 key");
1428                e
1429            })
1430    }
1431
1432    fn get_domain_ldap_allow_unix_pw_bind(&mut self) -> Result<bool, OperationError> {
1433        self.internal_search_uuid(UUID_DOMAIN_INFO).map(|entry| {
1434            entry
1435                .get_ava_single_bool(Attribute::LdapAllowUnixPwBind)
1436                .unwrap_or(true)
1437        })
1438    }
1439
1440    /// Get the password badlist from the system config. You should not call this directly
1441    /// as this value is cached in the system_config() value.
1442    fn get_sc_password_badlist(&mut self) -> Result<HashSet<String>, OperationError> {
1443        self.internal_search_uuid(UUID_SYSTEM_CONFIG)
1444            .map(|e| match e.get_ava_iter_iutf8(Attribute::BadlistPassword) {
1445                Some(vs_str_iter) => vs_str_iter.map(str::to_string).collect::<HashSet<_>>(),
1446                None => HashSet::default(),
1447            })
1448            .map_err(|e| {
1449                error!(
1450                    ?e,
1451                    "Failed to retrieve password badlist from system configuration"
1452                );
1453                e
1454            })
1455    }
1456
1457    /// Get the denied name set from the system config. You should not call this directly
1458    /// as this value is cached in the system_config() value.
1459    fn get_sc_denied_names(&mut self) -> Result<HashSet<String>, OperationError> {
1460        self.internal_search_uuid(UUID_SYSTEM_CONFIG)
1461            .map(|e| match e.get_ava_iter_iname(Attribute::DeniedName) {
1462                Some(vs_str_iter) => vs_str_iter.map(str::to_string).collect::<HashSet<_>>(),
1463                None => HashSet::default(),
1464            })
1465            .map_err(|e| {
1466                error!(
1467                    ?e,
1468                    "Failed to retrieve denied names from system configuration"
1469                );
1470                e
1471            })
1472    }
1473
1474    fn get_oauth2rs_set(&mut self) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
1475        self.internal_search(filter!(f_eq(
1476            Attribute::Class,
1477            EntryClass::OAuth2ResourceServer.into(),
1478        )))
1479    }
1480
1481    fn get_applications_set(&mut self) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
1482        self.internal_search(filter!(f_eq(
1483            Attribute::Class,
1484            EntryClass::Application.into(),
1485        )))
1486    }
1487
1488    #[instrument(level = "debug", skip_all)]
1489    fn consumer_get_state(&mut self) -> Result<ReplRuvRange, OperationError> {
1490        // Get the current state of "where we are up to"
1491        //
1492        // There are two approaches we can use here. We can either store a cookie
1493        // related to the supplier we are fetching from, or we can use our RUV state.
1494        //
1495        // Initially I'm using RUV state, because it lets us select exactly what has
1496        // changed, where the cookie approach is more coarse grained. The cookie also
1497        // requires some more knowledge about what supplier we are communicating too
1498        // where the RUV approach doesn't since the supplier calcs the diff.
1499        //
1500        // We need the RUV as a state of
1501        //
1502        // [ s_uuid, cid_min, cid_max ]
1503        // [ s_uuid, cid_min, cid_max ]
1504        // [ s_uuid, cid_min, cid_max ]
1505        // ...
1506        //
1507        // This way the remote can diff against it's knowledge and work out:
1508        //
1509        // [ s_uuid, from_cid, to_cid ]
1510        // [ s_uuid, from_cid, to_cid ]
1511        //
1512        // ...
1513
1514        let domain_uuid = self.get_domain_uuid();
1515
1516        // Which then the supplier will use to actually retrieve the set of entries.
1517        // and the needed attributes we need.
1518        let ruv_snapshot = self.get_be_txn().get_ruv();
1519
1520        // What's the current set of ranges?
1521        ruv_snapshot
1522            .current_ruv_range()
1523            .map(|ranges| ReplRuvRange::V1 {
1524                domain_uuid,
1525                ranges,
1526            })
1527    }
1528}
1529
1530// Actually conduct a search request
1531// This is the core of the server, as it processes the entire event
1532// applies all parts required in order and more.
1533impl<'a> QueryServerTransaction<'a> for QueryServerReadTransaction<'a> {
1534    type AccessControlsTransactionType = AccessControlsReadTransaction<'a>;
1535    type BackendTransactionType = BackendReadTransaction<'a>;
1536    type SchemaTransactionType = SchemaReadTransaction;
1537    type KeyProvidersTransactionType = KeyProvidersReadTransaction;
1538
1539    fn get_be_txn(&mut self) -> &mut BackendReadTransaction<'a> {
1540        &mut self.be_txn
1541    }
1542
1543    fn get_schema<'b>(&self) -> &'b SchemaReadTransaction {
1544        // Strip the lifetime here. Schema is a sub-component of the transaction and is
1545        // *never* changed excepting in a write TXN, so we want to allow the schema to
1546        // be borrowed while the rest of the read txn is under a mut.
1547        unsafe {
1548            let s = (&self.schema) as *const _;
1549            &*s
1550        }
1551    }
1552
1553    fn get_accesscontrols(&self) -> &AccessControlsReadTransaction<'a> {
1554        &self.accesscontrols
1555    }
1556
1557    fn get_key_providers(&self) -> &KeyProvidersReadTransaction {
1558        &self.key_providers
1559    }
1560
1561    fn get_resolve_filter_cache(&mut self) -> Option<&mut ResolveFilterCacheReadTxn<'a>> {
1562        Some(&mut self.resolve_filter_cache)
1563    }
1564
1565    fn get_feature_hmac_name_history_config(&self) -> &HmacNameHistoryConfig {
1566        &self.d_info.feature_config.hmac_name_history
1567    }
1568
1569    fn get_feature_account_signup_config(&self) -> &AccountSignupConfig {
1570        &self.d_info.feature_config.account_signup
1571    }
1572
1573    fn txn_name_to_uuid(&mut self) -> &mut BTreeMap<String, Uuid> {
1574        &mut self.txn_name_to_uuid
1575    }
1576
1577    fn get_resolve_filter_cache_and_be_txn(
1578        &mut self,
1579    ) -> (
1580        &mut BackendReadTransaction<'a>,
1581        Option<&mut ResolveFilterCacheReadTxn<'a>>,
1582    ) {
1583        (&mut self.be_txn, Some(&mut self.resolve_filter_cache))
1584    }
1585
1586    fn pw_badlist(&self) -> &HashSet<String> {
1587        &self.system_config.pw_badlist
1588    }
1589
1590    fn denied_names(&self) -> &HashSet<String> {
1591        &self.system_config.denied_names
1592    }
1593
1594    fn domain_info(&self) -> &DomainInfo {
1595        &self.d_info
1596    }
1597
1598    fn get_domain_version(&self) -> DomainVersion {
1599        self.d_info.d_vers
1600    }
1601
1602    fn get_domain_patch_level(&self) -> u32 {
1603        self.d_info.d_patch_level
1604    }
1605
1606    fn get_domain_development_taint(&self) -> bool {
1607        self.d_info.d_devel_taint
1608    }
1609
1610    fn get_domain_uuid(&self) -> Uuid {
1611        self.d_info.d_uuid
1612    }
1613
1614    fn get_domain_name(&self) -> &str {
1615        &self.d_info.d_name
1616    }
1617
1618    fn get_domain_display_name(&self) -> &str {
1619        &self.d_info.d_display
1620    }
1621
1622    fn get_domain_image_value(&self) -> Option<ImageValue> {
1623        self.d_info.d_image.clone()
1624    }
1625}
1626
1627impl QueryServerReadTransaction<'_> {
1628    pub(crate) fn trim_cid(&self) -> &Cid {
1629        &self.trim_cid
1630    }
1631
1632    /// Retrieve the domain info of this server
1633    pub fn public_domain_info(&mut self) -> Result<ProtoDomainInfo, OperationError> {
1634        let d_info = &self.d_info;
1635
1636        Ok(ProtoDomainInfo {
1637            name: d_info.d_name.clone(),
1638            displayname: d_info.d_display.clone(),
1639            uuid: d_info.d_uuid,
1640            level: d_info.d_vers,
1641        })
1642    }
1643
1644    /// Verify the data content of the server is as expected. This will probably
1645    /// call various functions for validation, including possibly plugin
1646    /// verifications.
1647    pub(crate) fn verify(&mut self) -> Vec<Result<(), ConsistencyError>> {
1648        // If we fail after backend, we need to return NOW because we can't
1649        // assert any other faith in the DB states.
1650        //  * backend
1651        let be_errs = self.get_be_txn().verify();
1652
1653        if !be_errs.is_empty() {
1654            return be_errs;
1655        }
1656
1657        //  * in memory schema consistency.
1658        let sc_errs = self.get_schema().validate();
1659
1660        if !sc_errs.is_empty() {
1661            return sc_errs;
1662        }
1663
1664        // The schema is now valid, so we load this up
1665
1666        //  * Indexing (req be + sch )
1667        let idx_errs = self.get_be_txn().verify_indexes();
1668
1669        if !idx_errs.is_empty() {
1670            return idx_errs;
1671        }
1672
1673        // If anything error to this point we can't trust the verifications below. From
1674        // here we can just amass results.
1675        let mut results = Vec::with_capacity(0);
1676
1677        // Verify all our entries. Weird flex I know, but it's needed for verifying
1678        // the entry changelogs are consistent to their entries.
1679        let schema = self.get_schema();
1680
1681        let filt_all = filter!(f_pres(Attribute::Class));
1682        let all_entries = match self.internal_search(filt_all) {
1683            Ok(a) => a,
1684            Err(_e) => return vec![Err(ConsistencyError::QueryServerSearchFailure)],
1685        };
1686
1687        for e in all_entries {
1688            e.verify(schema, &mut results)
1689        }
1690
1691        // Verify the RUV to the entry changelogs now.
1692        self.get_be_txn().verify_ruv(&mut results);
1693
1694        // Ok entries passed, lets move on to the content.
1695        // Most of our checks are in the plugins, so we let them
1696        // do their job.
1697
1698        // Now, call the plugins verification system.
1699        Plugins::run_verify(self, &mut results);
1700        // Finished
1701
1702        results
1703    }
1704
1705    #[instrument(level = "debug", skip_all)]
1706    pub fn scim_entry_id_get_ext(
1707        &mut self,
1708        uuid: Uuid,
1709        class: EntryClass,
1710        query: ScimEntryGetQuery,
1711        ident: Identity,
1712    ) -> Result<ScimEntryKanidm, OperationError> {
1713        let filter_intent = filter!(f_and!([
1714            f_eq(Attribute::Uuid, PartialValue::Uuid(uuid)),
1715            f_eq(Attribute::Class, class.into())
1716        ]));
1717
1718        let f_intent_valid = filter_intent
1719            .validate(self.get_schema())
1720            .map_err(OperationError::SchemaViolation)?;
1721
1722        let f_valid = f_intent_valid.clone().into_ignore_hidden();
1723
1724        let r_attrs = query
1725            .attributes
1726            .map(|attr_set| attr_set.into_iter().collect());
1727
1728        let se = SearchEvent {
1729            ident,
1730            filter: f_valid,
1731            filter_orig: f_intent_valid,
1732            attrs: r_attrs,
1733            effective_access_check: query.ext_access_check,
1734        };
1735
1736        let mut vs = self.search_ext(&se)?;
1737        match vs.pop() {
1738            Some(entry) if vs.is_empty() => entry.to_scim_kanidm(self),
1739            _ => {
1740                if vs.is_empty() {
1741                    Err(OperationError::NoMatchingEntries)
1742                } else {
1743                    // Multiple entries matched, should not be possible!
1744                    Err(OperationError::UniqueConstraintViolation)
1745                }
1746            }
1747        }
1748    }
1749
1750    #[instrument(level = "debug", skip_all)]
1751    pub fn scim_search_ext(
1752        &mut self,
1753        ident: Identity,
1754        filter: ScimFilter,
1755        query: ScimEntryGetQuery,
1756    ) -> Result<ScimListResponse, OperationError> {
1757        let filter = if let Some(ref user_filter) = query.filter {
1758            ScimFilter::And(Box::new(filter), Box::new(user_filter.clone()))
1759        } else {
1760            filter
1761        };
1762
1763        let filter_intent = Filter::from_scim_ro(&ident, &filter, self)
1764            .inspect_err(|err| error!(?err, "Unable to resolve scim filter"))?;
1765
1766        self.scim_search_filter_ext(ident, &filter_intent, query)
1767    }
1768
1769    pub fn scim_search_filter_ext(
1770        &mut self,
1771        ident: Identity,
1772        filter_intent: &Filter<FilterInvalid>,
1773        query: ScimEntryGetQuery,
1774    ) -> Result<ScimListResponse, OperationError> {
1775        let f_intent_valid = filter_intent
1776            .validate(self.get_schema())
1777            .map_err(OperationError::SchemaViolation)?;
1778
1779        let f_valid = f_intent_valid.clone().into_ignore_hidden();
1780
1781        let r_attrs = query
1782            .attributes
1783            .map(|attr_set| attr_set.into_iter().collect());
1784
1785        let se = SearchEvent {
1786            ident,
1787            filter: f_valid,
1788            filter_orig: f_intent_valid,
1789            attrs: r_attrs,
1790            effective_access_check: query.ext_access_check,
1791        };
1792
1793        let mut result_set = self.search_ext(&se)?;
1794
1795        // We need to know total_results before we paginate.
1796        let total_results = result_set.len() as u64;
1797
1798        // These are STUPID ways to do this, but they demonstrate that the feature
1799        // works and it's viable on small datasets. We will make this use indexes
1800        // in the future!
1801
1802        // First, sort if any.
1803        if let Some(sort_attr) = query.sort_by {
1804            result_set.sort_unstable_by(|entry_left, entry_right| {
1805                let left = entry_left.get_ava_set(&sort_attr);
1806                let right = entry_right.get_ava_set(&sort_attr);
1807                match (left, right) {
1808                    (Some(left), Some(right)) => left.cmp(right),
1809                    (Some(_), None) => std::cmp::Ordering::Less,
1810                    (None, Some(_)) => std::cmp::Ordering::Greater,
1811                    (None, None) => std::cmp::Ordering::Equal,
1812                }
1813            });
1814        }
1815
1816        // Paginate, if any.
1817        let (items_per_page, start_index, paginated_result_set) = if let Some(count) = query.count {
1818            let count: u64 = count.get();
1819            // User wants pagination. Count is how many elements they want.
1820
1821            let start_index: u64 = query
1822                .start_index
1823                .map(|non_zero_index|
1824                    // SCIM pagination is 1 indexed, not 0.
1825                    non_zero_index.get() - 1)
1826                .unwrap_or_default();
1827
1828            // First, check that our start_index is valid.
1829            if start_index as usize > result_set.len() {
1830                // SCIM rfc doesn't define what happens if start index
1831                // is OOB of the result set.
1832                return Err(OperationError::SC0029PaginationOutOfBounds);
1833            }
1834
1835            let mut result_set = result_set.split_off(start_index as usize);
1836            result_set.truncate(count as usize);
1837
1838            (
1839                NonZeroU64::new(count),
1840                NonZeroU64::new(start_index + 1),
1841                result_set,
1842            )
1843        } else {
1844            // Unchanged
1845            (None, None, result_set)
1846        };
1847
1848        let resources = paginated_result_set
1849            .into_iter()
1850            .map(|entry| entry.to_scim_kanidm(self))
1851            .collect::<Result<Vec<_>, _>>()?;
1852
1853        Ok(ScimListResponse {
1854            // Requires other schema changes in future.
1855            schemas: Vec::with_capacity(0),
1856            total_results,
1857            items_per_page,
1858            start_index,
1859            resources,
1860        })
1861    }
1862
1863    #[instrument(level = "debug", skip_all)]
1864    pub fn scim_search_message_ready_ext(
1865        &mut self,
1866        ident: Identity,
1867        curtime: Duration,
1868    ) -> Result<ScimListResponse, OperationError> {
1869        let curtime_odt = OffsetDateTime::UNIX_EPOCH + curtime;
1870
1871        let filter_intent = filter_all!(f_and(vec![
1872            f_eq(Attribute::Class, EntryClass::OutboundMessage.into()),
1873            f_lt(Attribute::SendAfter, PartialValue::DateTime(curtime_odt)),
1874            f_andnot(f_pres(Attribute::SentAt))
1875        ]));
1876
1877        let query = ScimEntryGetQuery::default();
1878
1879        self.scim_search_filter_ext(ident, &filter_intent, query)
1880    }
1881}
1882
1883impl<'a> QueryServerTransaction<'a> for QueryServerWriteTransaction<'a> {
1884    type AccessControlsTransactionType = AccessControlsWriteTransaction<'a>;
1885    type BackendTransactionType = BackendWriteTransaction<'a>;
1886    type SchemaTransactionType = SchemaWriteTransaction<'a>;
1887    type KeyProvidersTransactionType = KeyProvidersWriteTransaction<'a>;
1888
1889    fn get_be_txn(&mut self) -> &mut BackendWriteTransaction<'a> {
1890        &mut self.be_txn
1891    }
1892
1893    fn get_schema<'b>(&self) -> &'b SchemaWriteTransaction<'a> {
1894        // Strip the lifetime here. Schema is a sub-component of the transaction and is
1895        // *never* changed excepting in a write TXN, so we want to allow the schema to
1896        // be borrowed while the rest of the read txn is under a mut.
1897        unsafe {
1898            let s = (&self.schema) as *const _;
1899            &*s
1900        }
1901    }
1902
1903    fn get_accesscontrols(&self) -> &AccessControlsWriteTransaction<'a> {
1904        &self.accesscontrols
1905    }
1906
1907    fn get_key_providers(&self) -> &KeyProvidersWriteTransaction<'a> {
1908        &self.key_providers
1909    }
1910
1911    fn get_resolve_filter_cache(&mut self) -> Option<&mut ResolveFilterCacheReadTxn<'a>> {
1912        if self.resolve_filter_cache_clear || *self.phase < ServerPhase::SchemaReady {
1913            None
1914        } else {
1915            Some(&mut self.resolve_filter_cache)
1916        }
1917    }
1918
1919    fn get_feature_hmac_name_history_config(&self) -> &HmacNameHistoryConfig {
1920        &self.d_info.feature_config.hmac_name_history
1921    }
1922
1923    fn get_feature_account_signup_config(&self) -> &AccountSignupConfig {
1924        &self.d_info.feature_config.account_signup
1925    }
1926
1927    fn txn_name_to_uuid(&mut self) -> &mut BTreeMap<String, Uuid> {
1928        &mut self.txn_name_to_uuid
1929    }
1930
1931    fn get_resolve_filter_cache_and_be_txn(
1932        &mut self,
1933    ) -> (
1934        &mut BackendWriteTransaction<'a>,
1935        Option<&mut ResolveFilterCacheReadTxn<'a>>,
1936    ) {
1937        if self.resolve_filter_cache_clear || *self.phase < ServerPhase::SchemaReady {
1938            (&mut self.be_txn, None)
1939        } else {
1940            (&mut self.be_txn, Some(&mut self.resolve_filter_cache))
1941        }
1942    }
1943
1944    fn pw_badlist(&self) -> &HashSet<String> {
1945        &self.system_config.pw_badlist
1946    }
1947
1948    fn denied_names(&self) -> &HashSet<String> {
1949        &self.system_config.denied_names
1950    }
1951
1952    fn domain_info(&self) -> &DomainInfo {
1953        &self.d_info
1954    }
1955
1956    fn get_domain_version(&self) -> DomainVersion {
1957        self.d_info.d_vers
1958    }
1959
1960    fn get_domain_patch_level(&self) -> u32 {
1961        self.d_info.d_patch_level
1962    }
1963
1964    fn get_domain_development_taint(&self) -> bool {
1965        self.d_info.d_devel_taint
1966    }
1967
1968    fn get_domain_uuid(&self) -> Uuid {
1969        self.d_info.d_uuid
1970    }
1971
1972    /// Gets the in-memory domain_name element
1973    fn get_domain_name(&self) -> &str {
1974        &self.d_info.d_name
1975    }
1976
1977    fn get_domain_display_name(&self) -> &str {
1978        &self.d_info.d_display
1979    }
1980
1981    fn get_domain_image_value(&self) -> Option<ImageValue> {
1982        self.d_info.d_image.clone()
1983    }
1984}
1985
1986impl QueryServer {
1987    pub fn new(
1988        be: Backend,
1989        schema: Schema,
1990        domain_name: String,
1991        curtime: Duration,
1992    ) -> Result<Self, OperationError> {
1993        let (s_uuid, d_uuid, ts_max) = {
1994            let mut wr = be.write()?;
1995            let s_uuid = wr.get_db_s_uuid()?;
1996            let d_uuid = wr.get_db_d_uuid()?;
1997            let ts_max = wr.get_db_ts_max(curtime)?;
1998            wr.commit()?;
1999            (s_uuid, d_uuid, ts_max)
2000        };
2001
2002        let pool_size = be.get_pool_size();
2003
2004        debug!("Server UUID -> {:?}", s_uuid);
2005        debug!("Domain UUID -> {:?}", d_uuid);
2006        debug!("Domain Name -> {:?}", domain_name);
2007
2008        let d_info = Arc::new(CowCell::new(DomainInfo {
2009            d_uuid,
2010            // Start with our level as zero.
2011            // This will be reloaded from the DB shortly :)
2012            d_vers: DOMAIN_LEVEL_0,
2013            d_patch_level: 0,
2014            d_name: domain_name.clone(),
2015            // we set the domain_display_name to the configuration file's domain_name
2016            // here because the database is not started, so we cannot pull it from there.
2017            d_display: domain_name,
2018            // Automatically derive our current taint mode based on the PRERELEASE setting.
2019            d_devel_taint: option_env!("KANIDM_PRE_RELEASE").is_some(),
2020            d_ldap_allow_unix_pw_bind: false,
2021            d_allow_easter_eggs: false,
2022            d_allow_account_recovery: false,
2023            d_image: None,
2024            feature_config: FeatureConfig::default(),
2025        }));
2026
2027        let cid = Cid::new_lamport(s_uuid, curtime, &ts_max);
2028        let cid_max = Arc::new(CowCell::new(cid));
2029
2030        // These default to empty, but they'll be populated shortly.
2031        let system_config = Arc::new(CowCell::new(SystemConfig::default()));
2032
2033        let dyngroup_cache = Arc::new(CowCell::new(DynGroupCache::default()));
2034
2035        let phase = Arc::new(CowCell::new(ServerPhase::Bootstrap));
2036
2037        let resolve_filter_cache = Arc::new(
2038            ARCacheBuilder::new()
2039                .set_size(RESOLVE_FILTER_CACHE_MAX, RESOLVE_FILTER_CACHE_LOCAL)
2040                .set_reader_quiesce(true)
2041                .build()
2042                .ok_or_else(|| {
2043                    error!("Failed to build filter resolve cache");
2044                    OperationError::DB0003FilterResolveCacheBuild
2045                })?,
2046        );
2047
2048        let key_providers = Arc::new(KeyProviders::default());
2049
2050        // These needs to be pool_size minus one to always leave a DB ticket
2051        // for a writer. But it also needs to be at least one :)
2052        debug_assert!(pool_size > 0);
2053        let read_ticket_pool = std::cmp::max(pool_size - 1, 1);
2054
2055        Ok(QueryServer {
2056            phase,
2057            d_info,
2058            system_config,
2059            be,
2060            schema: Arc::new(schema),
2061            accesscontrols: Arc::new(AccessControls::default()),
2062            db_tickets: Arc::new(Semaphore::new(pool_size as usize)),
2063            read_tickets: Arc::new(Semaphore::new(read_ticket_pool as usize)),
2064            write_ticket: Arc::new(Semaphore::new(1)),
2065            resolve_filter_cache,
2066            dyngroup_cache,
2067            cid_max,
2068            key_providers,
2069        })
2070    }
2071
2072    pub fn try_quiesce(&self) {
2073        self.be.try_quiesce();
2074        self.accesscontrols.try_quiesce();
2075        self.resolve_filter_cache.try_quiesce();
2076    }
2077
2078    #[instrument(level = "debug", skip_all)]
2079    async fn read_acquire_ticket(&self) -> Option<(SemaphorePermit<'_>, SemaphorePermit<'_>)> {
2080        // Get a read ticket. Basically this forces us to queue with other readers, while preventing
2081        // us from competing with writers on the db tickets. This tilts us to write prioritising
2082        // on db operations by always making sure a writer can get a db ticket.
2083        let read_ticket = if cfg!(test) {
2084            self.read_tickets
2085                .try_acquire()
2086                .inspect_err(|err| {
2087                    error!(?err, "Unable to acquire read ticket!");
2088                })
2089                .ok()?
2090        } else {
2091            let fut = tokio::time::timeout(
2092                Duration::from_millis(DB_LOCK_ACQUIRE_TIMEOUT_MILLIS),
2093                self.read_tickets.acquire(),
2094            );
2095
2096            match fut.await {
2097                Ok(Ok(ticket)) => ticket,
2098                Ok(Err(_)) => {
2099                    error!("Failed to acquire read ticket, may be poisoned.");
2100                    return None;
2101                }
2102                Err(_) => {
2103                    error!("Failed to acquire read ticket, server is overloaded.");
2104                    return None;
2105                }
2106            }
2107        };
2108
2109        // We need to ensure a db conn will be available. At this point either a db ticket
2110        // *must* be available because pool_size >= 2 and the only other holders are write
2111        // and read ticket holders, OR pool_size == 1, and we are waiting on the writer to now
2112        // complete.
2113        let db_ticket = if cfg!(test) {
2114            self.db_tickets
2115                .try_acquire()
2116                .inspect_err(|err| {
2117                    error!(?err, "Unable to acquire database ticket!");
2118                })
2119                .ok()?
2120        } else {
2121            self.db_tickets
2122                .acquire()
2123                .await
2124                .inspect_err(|err| {
2125                    error!(?err, "Unable to acquire database ticket!");
2126                })
2127                .ok()?
2128        };
2129
2130        Some((read_ticket, db_ticket))
2131    }
2132
2133    pub async fn read(&self) -> Result<QueryServerReadTransaction<'_>, OperationError> {
2134        let (read_ticket, db_ticket) = self
2135            .read_acquire_ticket()
2136            .await
2137            .ok_or(OperationError::DatabaseLockAcquisitionTimeout)?;
2138        // Point of no return - we now have a DB thread AND the read ticket, we MUST complete
2139        // as soon as possible! The following locks and elements below are SYNCHRONOUS but
2140        // will never be contented at this point, and will always progress.
2141        let schema = self.schema.read();
2142
2143        let cid_max = self.cid_max.read();
2144        let trim_cid = cid_max.sub_secs(CHANGELOG_MAX_AGE)?;
2145
2146        let be_txn = self.be.read()?;
2147
2148        Ok(QueryServerReadTransaction {
2149            be_txn,
2150            schema,
2151            d_info: self.d_info.read(),
2152            system_config: self.system_config.read(),
2153            accesscontrols: self.accesscontrols.read(),
2154            key_providers: self.key_providers.read(),
2155            _db_ticket: db_ticket,
2156            _read_ticket: read_ticket,
2157            resolve_filter_cache: self.resolve_filter_cache.read(),
2158            trim_cid,
2159            txn_name_to_uuid: Default::default(),
2160        })
2161    }
2162
2163    #[instrument(level = "debug", skip_all)]
2164    async fn write_acquire_ticket(&self) -> Option<(SemaphorePermit<'_>, SemaphorePermit<'_>)> {
2165        // Guarantee we are the only writer on the thread pool
2166        let write_ticket = if cfg!(test) {
2167            self.write_ticket
2168                .try_acquire()
2169                .inspect_err(|err| {
2170                    error!(?err, "Unable to acquire write ticket!");
2171                })
2172                .ok()?
2173        } else {
2174            let fut = tokio::time::timeout(
2175                Duration::from_millis(DB_LOCK_ACQUIRE_TIMEOUT_MILLIS),
2176                self.write_ticket.acquire(),
2177            );
2178
2179            match fut.await {
2180                Ok(Ok(ticket)) => ticket,
2181                Ok(Err(_)) => {
2182                    error!("Failed to acquire write ticket, may be poisoned.");
2183                    return None;
2184                }
2185                Err(_) => {
2186                    error!("Failed to acquire write ticket, server is overloaded.");
2187                    return None;
2188                }
2189            }
2190        };
2191
2192        // We need to ensure a db conn will be available. At this point either a db ticket
2193        // *must* be available because pool_size >= 2 and the only other are readers, or
2194        // pool_size == 1 and we are waiting on a single reader to now complete
2195        let db_ticket = if cfg!(test) {
2196            self.db_tickets
2197                .try_acquire()
2198                .inspect_err(|err| {
2199                    error!(?err, "Unable to acquire write db_ticket!");
2200                })
2201                .ok()?
2202        } else {
2203            self.db_tickets
2204                .acquire()
2205                .await
2206                .inspect_err(|err| {
2207                    error!(?err, "Unable to acquire write db_ticket!");
2208                })
2209                .ok()?
2210        };
2211
2212        Some((write_ticket, db_ticket))
2213    }
2214
2215    pub async fn write(
2216        &self,
2217        curtime: Duration,
2218    ) -> Result<QueryServerWriteTransaction<'_>, OperationError> {
2219        let (write_ticket, db_ticket) = self
2220            .write_acquire_ticket()
2221            .await
2222            .ok_or(OperationError::DatabaseLockAcquisitionTimeout)?;
2223
2224        // Point of no return - we now have a DB thread AND the write ticket, we MUST complete
2225        // as soon as possible! The following locks and elements below are SYNCHRONOUS but
2226        // will never be contented at this point, and will always progress.
2227
2228        let be_txn = self.be.write()?;
2229
2230        let schema_write = self.schema.write();
2231        let d_info = self.d_info.write();
2232        let system_config = self.system_config.write();
2233        let phase = self.phase.write();
2234
2235        let mut cid = self.cid_max.write();
2236        // Update the cid now.
2237        *cid = Cid::new_lamport(cid.s_uuid, curtime, &cid.ts);
2238
2239        let trim_cid = cid.sub_secs(CHANGELOG_MAX_AGE)?;
2240
2241        Ok(QueryServerWriteTransaction {
2242            // I think this is *not* needed, because commit is mut self which should
2243            // take ownership of the value, and cause the commit to "only be run
2244            // once".
2245            //
2246            // The committed flag is however used for abort-specific code in drop
2247            // which today I don't think we have ... yet.
2248            committed: false,
2249            phase,
2250            d_info,
2251            system_config,
2252            curtime,
2253            cid,
2254            trim_cid,
2255            be_txn,
2256            schema: schema_write,
2257            accesscontrols: self.accesscontrols.write(),
2258            changed_flags: ChangeFlag::empty(),
2259            changed_uuid: HashSet::new(),
2260            _db_ticket: db_ticket,
2261            _write_ticket: write_ticket,
2262            resolve_filter_cache: self.resolve_filter_cache.read(),
2263            resolve_filter_cache_clear: false,
2264            resolve_filter_cache_write: self.resolve_filter_cache.write(),
2265            dyngroup_cache: self.dyngroup_cache.write(),
2266            key_providers: self.key_providers.write(),
2267            txn_name_to_uuid: Default::default(),
2268        })
2269    }
2270
2271    #[cfg(any(test, debug_assertions))]
2272    pub async fn clear_cache(&self) -> Result<(), OperationError> {
2273        let ct = duration_from_epoch_now();
2274        let mut w_txn = self.write(ct).await?;
2275        w_txn.clear_cache()?;
2276        w_txn.commit()
2277    }
2278
2279    pub async fn verify(&self) -> Vec<Result<(), ConsistencyError>> {
2280        let current_time = duration_from_epoch_now();
2281        // Before we can proceed, command the QS to load schema in full.
2282        // IMPORTANT: While we take a write txn, this does no writes to the
2283        // actual db, it's only so we can write to the in memory schema
2284        // structures.
2285        if self
2286            .write(current_time)
2287            .await
2288            .and_then(|mut txn| {
2289                txn.force_schema_reload();
2290                txn.commit()
2291            })
2292            .is_err()
2293        {
2294            return vec![Err(ConsistencyError::Unknown)];
2295        };
2296
2297        match self.read().await {
2298            Ok(mut r_txn) => r_txn.verify(),
2299            Err(_) => vec![Err(ConsistencyError::Unknown)],
2300        }
2301    }
2302}
2303
2304impl<'a> QueryServerWriteTransaction<'a> {
2305    pub(crate) fn get_server_uuid(&self) -> Uuid {
2306        // Cid has our server id within
2307        self.cid.s_uuid
2308    }
2309
2310    pub(crate) fn reset_server_uuid(&mut self) -> Result<(), OperationError> {
2311        let s_uuid = self.be_txn.reset_db_s_uuid().map_err(|err| {
2312            error!(?err, "Failed to reset server replication uuid");
2313            err
2314        })?;
2315
2316        debug!(?s_uuid, "reset server replication uuid");
2317
2318        self.cid.s_uuid = s_uuid;
2319
2320        Ok(())
2321    }
2322
2323    pub(crate) fn get_curtime(&self) -> Duration {
2324        self.curtime
2325    }
2326
2327    pub(crate) fn get_curtime_odt(&self) -> OffsetDateTime {
2328        OffsetDateTime::UNIX_EPOCH + self.curtime
2329    }
2330
2331    pub(crate) fn get_cid(&self) -> &Cid {
2332        &self.cid
2333    }
2334
2335    pub(crate) fn get_key_providers_mut(&mut self) -> &mut KeyProvidersWriteTransaction<'a> {
2336        &mut self.key_providers
2337    }
2338
2339    pub(crate) fn get_dyngroup_cache(&mut self) -> &mut DynGroupCache {
2340        &mut self.dyngroup_cache
2341    }
2342
2343    pub fn domain_raise(&mut self, level: u32) -> Result<(), OperationError> {
2344        if level > DOMAIN_MAX_LEVEL {
2345            return Err(OperationError::MG0002RaiseDomainLevelExceedsMaximum);
2346        }
2347
2348        let modl = ModifyList::new_purge_and_set(Attribute::Version, Value::Uint32(level));
2349        let udi = PVUUID_DOMAIN_INFO.clone();
2350        let filt = filter_all!(f_eq(Attribute::Uuid, udi));
2351        self.internal_modify(&filt, &modl)
2352    }
2353
2354    pub fn domain_remigrate(&mut self, level: u32) -> Result<(), OperationError> {
2355        let mut_d_info = self.d_info.get_mut();
2356
2357        // NOTE: See reload_domain_info_version which asserts that we are not attempting
2358        // an unsupported remigration. This check is just a smoke check to no-op if we
2359        // are not requesting any meaningful action.
2360        if level > mut_d_info.d_vers {
2361            // Nothing to do.
2362            return Ok(());
2363        };
2364
2365        info!(
2366            "Preparing to re-migrate from {} -> {}",
2367            level, mut_d_info.d_vers
2368        );
2369        mut_d_info.d_vers = level;
2370        self.changed_flags.insert(ChangeFlag::DOMAIN);
2371
2372        Ok(())
2373    }
2374
2375    #[instrument(level = "debug", skip_all)]
2376    pub(crate) fn reload_schema(&mut self) -> Result<(), OperationError> {
2377        match self.get_domain_version() {
2378            /*
2379            0 => {
2380                // server is being brought up, so the schema was already set by a caller.
2381            }
2382            */
2383            level if level < DOMAIN_LEVEL_1_11 => {
2384                // supply entries to the writable schema to reload from.
2385                // find all attributes.
2386                let filt = filter!(f_eq(Attribute::Class, EntryClass::AttributeType.into()));
2387                let res = self.internal_search(filt).map_err(|e| {
2388                    error!("reload schema internal search failed {:?}", e);
2389                    e
2390                })?;
2391                // load them.
2392                let attributetypes: Result<Vec<_>, _> =
2393                    res.iter().map(|e| SchemaAttribute::try_from(e)).collect();
2394
2395                let attributetypes = attributetypes.map_err(|e| {
2396                    error!("reload schema attributetypes {:?}", e);
2397                    e
2398                })?;
2399
2400                // IMPORTANT: If attribute types is empty, it's because we are in "in memory schema"
2401                // mode only. This is a horrid hack but it's needed for backwards compat for now.
2402                //
2403                // The reason it's needed is that at this phase in bootstrap, domain_version is 0
2404                // but the on-disk schema mode relies on that to trigger a read from the DB. We can't
2405                // gate on version == 0 because that breaks the older versions. But if we DONT do
2406                // anything then this call will nuke the in memory schema that we just setup causing
2407                // the server to fail.
2408                if attributetypes.is_empty() {
2409                    debug!("DB attributes are empty - we are probably in DL_1_11 memory only schema mode.");
2410                } else {
2411                    self.schema
2412                        .update_attributes(attributetypes.into_iter())
2413                        .map_err(|e| {
2414                            error!("reload schema update attributetypes {:?}", e);
2415                            e
2416                        })?;
2417
2418                    // find all classes
2419                    let filt = filter!(f_eq(Attribute::Class, EntryClass::ClassType.into()));
2420                    let res = self.internal_search(filt).map_err(|e| {
2421                        error!("reload schema internal search failed {:?}", e);
2422                        e
2423                    })?;
2424                    // load them.
2425                    let classtypes: Result<Vec<_>, _> =
2426                        res.iter().map(|e| SchemaClass::try_from(e)).collect();
2427                    let classtypes = classtypes.map_err(|e| {
2428                        error!("reload schema classtypes {:?}", e);
2429                        e
2430                    })?;
2431
2432                    self.schema
2433                        .update_classes(classtypes.into_iter())
2434                        .map_err(|e| {
2435                            error!("reload schema update classtypes {:?}", e);
2436                            e
2437                        })?;
2438
2439                    // validate.
2440                    let valid_r = self.schema.validate();
2441
2442                    // Translate the result.
2443                    if !valid_r.is_empty() {
2444                        // Log the failures
2445                        error!("Schema reload failed -> {:?}", valid_r);
2446                        return Err(OperationError::ConsistencyError(
2447                            valid_r.into_iter().filter_map(|v| v.err()).collect(),
2448                        ));
2449                    };
2450                }
2451            }
2452            DOMAIN_LEVEL_1_11 => self.migrate_schema_1_11()?,
2453            DOMAIN_LEVEL_1_12 => self.migrate_schema_1_12()?,
2454            DOMAIN_LEVEL_1_13 => self.migrate_schema_1_13()?,
2455            _ => {
2456                debug_assert!(false, "domain level was not configured in reload_schema");
2457                return Err(OperationError::MG0001InvalidReMigrationLevel);
2458            }
2459        }
2460
2461        // Now use this to reload the backend idxmeta
2462        trace!("Reloading idxmeta ...");
2463        self.be_txn
2464            .update_idxmeta(self.schema.reload_idxmeta())
2465            .inspect_err(|err| {
2466                error!(?err, "reload schema update idxmeta");
2467            })?;
2468
2469        // Since we reloaded the schema, we need to reload the filter cache since it
2470        // may have incorrect or outdated information about indexes now.
2471        self.resolve_filter_cache_clear = true;
2472
2473        // Trigger reloads on services that require post-schema reloads.
2474        // Mainly this is plugins.
2475        DynGroup::reload(self)?;
2476
2477        Ok(())
2478    }
2479
2480    #[instrument(level = "debug", skip_all)]
2481    fn reload_accesscontrols(&mut self) -> Result<(), OperationError> {
2482        // supply entries to the writable access controls to reload from.
2483        // This has to be done in FOUR passes - one for each type!
2484        //
2485        // Note, we have to do the search, parse, then submit here, because of the
2486        // requirement to have the write query server reference in the parse stage - this
2487        // would cause a rust double-borrow if we had AccessControls to try to handle
2488        // the entry lists themself.
2489        trace!("ACP reload started ...");
2490
2491        // Update the set of sync agreements
2492
2493        let filt = filter!(f_eq(Attribute::Class, EntryClass::SyncAccount.into()));
2494
2495        let res = self.internal_search(filt).map_err(|e| {
2496            admin_error!(
2497                err = ?e,
2498                "reload accesscontrols internal search failed",
2499            );
2500            e
2501        })?;
2502
2503        let sync_agreement_map: HashMap<Uuid, BTreeSet<Attribute>> = res
2504            .iter()
2505            .filter_map(|e| {
2506                e.get_ava_as_iutf8(Attribute::SyncYieldAuthority)
2507                    .map(|set| {
2508                        let set: BTreeSet<_> =
2509                            set.iter().map(|s| Attribute::from(s.as_str())).collect();
2510                        (e.get_uuid(), set)
2511                    })
2512            })
2513            .collect();
2514
2515        self.accesscontrols
2516            .update_sync_agreements(sync_agreement_map);
2517
2518        // Update search
2519        let filt = filter!(f_and!([
2520            f_eq(Attribute::Class, EntryClass::AccessControlProfile.into()),
2521            f_eq(Attribute::Class, EntryClass::AccessControlSearch.into()),
2522            f_andnot(f_eq(Attribute::AcpEnable, PV_FALSE.clone())),
2523        ]));
2524
2525        let res = self.internal_search(filt).map_err(|e| {
2526            admin_error!(
2527                err = ?e,
2528                "reload accesscontrols internal search failed",
2529            );
2530            e
2531        })?;
2532        let search_acps: Result<Vec<_>, _> = res
2533            .iter()
2534            .map(|e| AccessControlSearch::try_from(self, e))
2535            .collect();
2536
2537        let search_acps = search_acps.map_err(|e| {
2538            admin_error!(err = ?e, "Unable to parse search accesscontrols");
2539            e
2540        })?;
2541
2542        self.accesscontrols
2543            .update_search(search_acps)
2544            .map_err(|e| {
2545                admin_error!(err = ?e, "Failed to update search accesscontrols");
2546                e
2547            })?;
2548        // Update create
2549        let filt = filter!(f_and!([
2550            f_eq(Attribute::Class, EntryClass::AccessControlProfile.into()),
2551            f_eq(Attribute::Class, EntryClass::AccessControlCreate.into()),
2552            f_andnot(f_eq(Attribute::AcpEnable, PV_FALSE.clone())),
2553        ]));
2554
2555        let res = self.internal_search(filt).map_err(|e| {
2556            admin_error!(
2557                err = ?e,
2558                "reload accesscontrols internal search failed"
2559            );
2560            e
2561        })?;
2562        let create_acps: Result<Vec<_>, _> = res
2563            .iter()
2564            .map(|e| AccessControlCreate::try_from(self, e))
2565            .collect();
2566
2567        let create_acps = create_acps.map_err(|e| {
2568            admin_error!(err = ?e, "Unable to parse create accesscontrols");
2569            e
2570        })?;
2571
2572        self.accesscontrols
2573            .update_create(create_acps)
2574            .map_err(|e| {
2575                admin_error!(err = ?e, "Failed to update create accesscontrols");
2576                e
2577            })?;
2578        // Update modify
2579        let filt = filter!(f_and!([
2580            f_eq(Attribute::Class, EntryClass::AccessControlProfile.into()),
2581            f_eq(Attribute::Class, EntryClass::AccessControlModify.into()),
2582            f_andnot(f_eq(Attribute::AcpEnable, PV_FALSE.clone())),
2583        ]));
2584
2585        let res = self.internal_search(filt).map_err(|e| {
2586            admin_error!("reload accesscontrols internal search failed {:?}", e);
2587            e
2588        })?;
2589        let modify_acps: Result<Vec<_>, _> = res
2590            .iter()
2591            .map(|e| AccessControlModify::try_from(self, e))
2592            .collect();
2593
2594        let modify_acps = modify_acps.map_err(|e| {
2595            admin_error!("Unable to parse modify accesscontrols {:?}", e);
2596            e
2597        })?;
2598
2599        self.accesscontrols
2600            .update_modify(modify_acps)
2601            .map_err(|e| {
2602                admin_error!("Failed to update modify accesscontrols {:?}", e);
2603                e
2604            })?;
2605        // Update delete
2606        let filt = filter!(f_and!([
2607            f_eq(Attribute::Class, EntryClass::AccessControlProfile.into()),
2608            f_eq(Attribute::Class, EntryClass::AccessControlDelete.into()),
2609            f_andnot(f_eq(Attribute::AcpEnable, PV_FALSE.clone())),
2610        ]));
2611
2612        let res = self.internal_search(filt).map_err(|e| {
2613            admin_error!("reload accesscontrols internal search failed {:?}", e);
2614            e
2615        })?;
2616        let delete_acps: Result<Vec<_>, _> = res
2617            .iter()
2618            .map(|e| AccessControlDelete::try_from(self, e))
2619            .collect();
2620
2621        let delete_acps = delete_acps.map_err(|e| {
2622            admin_error!("Unable to parse delete accesscontrols {:?}", e);
2623            e
2624        })?;
2625
2626        self.accesscontrols.update_delete(delete_acps).map_err(|e| {
2627            admin_error!("Failed to update delete accesscontrols {:?}", e);
2628            e
2629        })
2630    }
2631
2632    #[instrument(level = "debug", skip_all)]
2633    pub(crate) fn reload_key_material(&mut self) -> Result<(), OperationError> {
2634        let filt = filter!(f_eq(Attribute::Class, EntryClass::KeyProvider.into()));
2635
2636        let res = self.internal_search(filt).map_err(|e| {
2637            admin_error!(
2638                err = ?e,
2639                "reload key providers internal search failed",
2640            );
2641            e
2642        })?;
2643
2644        // FUTURE: During this reload we may need to access the PIN or other data
2645        // to access the provider.
2646        let providers = res
2647            .iter()
2648            .map(|e| KeyProvider::try_from(e).and_then(|kp| kp.test().map(|()| kp)))
2649            .collect::<Result<Vec<_>, _>>()?;
2650
2651        self.key_providers.update_providers(providers)?;
2652
2653        let filt = filter!(f_eq(Attribute::Class, EntryClass::KeyObject.into()));
2654
2655        let res = self.internal_search(filt).map_err(|e| {
2656            admin_error!(
2657                err = ?e,
2658                "reload key objects internal search failed",
2659            );
2660            e
2661        })?;
2662
2663        res.iter()
2664            .try_for_each(|entry| self.key_providers.load_key_object(entry.as_ref()))
2665    }
2666
2667    #[instrument(level = "debug", skip_all)]
2668    pub(crate) fn reload_system_config(&mut self) -> Result<(), OperationError> {
2669        let denied_names = self.get_sc_denied_names()?;
2670        let pw_badlist = self.get_sc_password_badlist()?;
2671
2672        let mut_system_config = self.system_config.get_mut();
2673        mut_system_config.denied_names = denied_names;
2674        mut_system_config.pw_badlist = pw_badlist;
2675        Ok(())
2676    }
2677
2678    /// Pulls the domain name from the database and updates the DomainInfo data in memory
2679    #[instrument(level = "debug", skip_all)]
2680    pub(crate) fn reload_domain_info_version(&mut self) -> Result<(), OperationError> {
2681        let domain_info = self.internal_search_uuid(UUID_DOMAIN_INFO).map_err(|err| {
2682            error!(?err, "Error getting domain info");
2683            err
2684        })?;
2685
2686        let domain_info_version = domain_info
2687            .get_ava_single_uint32(Attribute::Version)
2688            .ok_or_else(|| {
2689                error!("domain info missing attribute version");
2690                OperationError::InvalidEntryState
2691            })?;
2692
2693        let domain_info_patch_level = domain_info
2694            .get_ava_single_uint32(Attribute::PatchLevel)
2695            .unwrap_or(0);
2696
2697        // If we have moved from stable to dev, this triggers the taint. If we
2698        // are moving from dev to stable, the db will be true triggering the
2699        // taint flag. If we are stable to stable this will be false.
2700        let current_devel_flag = option_env!("KANIDM_PRE_RELEASE").is_some();
2701        let domain_info_devel_taint = current_devel_flag
2702            || domain_info
2703                .get_ava_single_bool(Attribute::DomainDevelopmentTaint)
2704                .unwrap_or_default();
2705
2706        let domain_allow_easter_eggs = domain_info
2707            .get_ava_single_bool(Attribute::DomainAllowEasterEggs)
2708            // This defaults to false for release versions, and true in development
2709            .unwrap_or(option_env!("KANIDM_PRE_RELEASE").is_some());
2710
2711        let domain_allow_account_recovery = domain_info
2712            .get_ava_single_bool(Attribute::DomainAllowAccountRecovery)
2713            .unwrap_or_default();
2714
2715        // We have to set the domain version here so that features which check for it
2716        // will now see it's been increased. This also prevents recursion during reloads
2717        // inside of a domain migration.
2718        let mut_d_info = self.d_info.get_mut();
2719        debug!(?mut_d_info);
2720        // This is the value that is set as part of re-migrate.
2721        let previous_version = mut_d_info.d_vers;
2722        let previous_patch_level = mut_d_info.d_patch_level;
2723        mut_d_info.d_vers = domain_info_version;
2724        mut_d_info.d_patch_level = domain_info_patch_level;
2725        mut_d_info.d_devel_taint = domain_info_devel_taint;
2726        mut_d_info.d_allow_easter_eggs = domain_allow_easter_eggs;
2727        mut_d_info.d_allow_account_recovery = domain_allow_account_recovery;
2728
2729        debug!(?mut_d_info);
2730
2731        // We must both be at the correct domain version *and* the correct patch level. If we are
2732        // not, then we only proceed to migrate *if* our server boot phase is correct.
2733        if (previous_version == domain_info_version
2734            && previous_patch_level == domain_info_patch_level)
2735            || *self.phase < ServerPhase::DomainInfoReady
2736        {
2737            return Ok(());
2738        }
2739
2740        debug!(domain_previous_version = ?previous_version, domain_target_version = ?domain_info_version);
2741        debug!(domain_previous_patch_level = ?previous_patch_level, domain_target_patch_level = ?domain_info_patch_level);
2742
2743        // We have to check for DL0 since that's the initialisation level. If we are at DL0 then
2744        // the server was just brought up and there are no other actions to take since we are
2745        // now at TGT level.
2746        if previous_version == DOMAIN_LEVEL_0 {
2747            debug!(
2748                "Server was just brought up, skipping migrations as we are already at target level"
2749            );
2750            return Ok(());
2751        }
2752
2753        if previous_version < DOMAIN_MIN_REMIGRATION_LEVEL {
2754            let valid_levels: Vec<_> =
2755                (DOMAIN_MIN_REMIGRATION_LEVEL..DOMAIN_PREVIOUS_TGT_LEVEL).collect();
2756            error!("UNABLE TO PROCEED. You have requested an initial migration level which is lower than supported.");
2757            error!("For more see: https://kanidm.github.io/kanidm/stable/support.html#upgrade-policy and https://kanidm.github.io/kanidm/stable/server_updates.html");
2758            error!(domain_previous_version = ?previous_version, domain_target_version = ?domain_info_version);
2759            error!(domain_previous_patch_level = ?previous_patch_level, domain_target_patch_level = ?domain_info_patch_level);
2760            error!(?valid_levels);
2761
2762            debug_assert!(false);
2763
2764            return Err(OperationError::MG0001InvalidReMigrationLevel);
2765        }
2766
2767        // Commented as an example of patch application
2768        /*
2769        if previous_patch_level < PATCH_LEVEL_2
2770            && domain_info_patch_level >= PATCH_LEVEL_2
2771            && domain_info_version == DOMAIN_LEVEL_9
2772        {
2773            self.migrate_domain_patch_level_2()?;
2774        }
2775        */
2776
2777        // This is to catch during development if we incorrectly move MIN_REMIGRATION but
2778        // without actually updating these values correctly.
2779        const { assert!(DOMAIN_MIN_REMIGRATION_LEVEL <= DOMAIN_PREVIOUS_TGT_LEVEL) };
2780        const { assert!(DOMAIN_MIN_REMIGRATION_LEVEL >= DOMAIN_MIN_CREATION_LEVEL) };
2781
2782        const { assert!(DOMAIN_MIN_CREATION_LEVEL >= DOMAIN_LEVEL_12) };
2783
2784        //                     /--- This needs to be the minimum creation level.
2785        //                     |                                          /-- This is the minlevel we can remigrate from
2786        //                     v                                          v
2787        if previous_version <= DOMAIN_LEVEL_11 && domain_info_version >= DOMAIN_LEVEL_12 {
2788            // 1.7 -> 1.8
2789            self.migrate_domain_11_to_12()?;
2790        }
2791
2792        if previous_version <= DOMAIN_LEVEL_12 && domain_info_version >= DOMAIN_LEVEL_13 {
2793            // 1.8 -> 1.9
2794            self.migrate_domain_12_to_13()?;
2795        }
2796
2797        if previous_version <= DOMAIN_LEVEL_13 && domain_info_version >= DOMAIN_LEVEL_14 {
2798            // 1.9 -> 1.10
2799            self.migrate_domain_13_to_14()?;
2800        }
2801
2802        if previous_version <= DOMAIN_LEVEL_14 && domain_info_version >= DOMAIN_LEVEL_1_11 {
2803            // 1.10 -> 1.11
2804            self.migrate_domain_1_10_to_1_11()?;
2805        }
2806
2807        if previous_version <= DOMAIN_LEVEL_1_11 && domain_info_version >= DOMAIN_LEVEL_1_12 {
2808            // 1.11 -> 1.12
2809            self.migrate_domain_1_11_to_1_12()?;
2810        }
2811
2812        if previous_version <= DOMAIN_LEVEL_1_12 && domain_info_version >= DOMAIN_LEVEL_1_13 {
2813            // 1.12 -> 1.13
2814            self.migrate_domain_1_12_to_1_13()?;
2815        }
2816
2817        if previous_version <= DOMAIN_LEVEL_1_13 && domain_info_version >= DOMAIN_LEVEL_1_14 {
2818            // 1.13 -> 1.14
2819            self.migrate_domain_1_13_to_1_14()?;
2820        }
2821
2822        // This is here to catch when we increase domain levels but didn't create the migration
2823        // hooks. If this fails it probably means you need to add another migration hook
2824        // in the above.
2825        const { assert!(DOMAIN_MAX_LEVEL == DOMAIN_LEVEL_1_14) };
2826        debug_assert!(domain_info_version <= DOMAIN_MAX_LEVEL);
2827
2828        Ok(())
2829    }
2830
2831    /// Pulls the domain name from the database and updates the DomainInfo data in memory
2832    #[instrument(level = "debug", skip_all)]
2833    pub(crate) fn reload_domain_info(&mut self) -> Result<(), OperationError> {
2834        let domain_entry = self.get_db_domain()?;
2835
2836        let domain_name = domain_entry
2837            .get_ava_single_iname(Attribute::DomainName)
2838            .map(str::to_string)
2839            .ok_or(OperationError::InvalidEntryState)?;
2840
2841        let display_name = domain_entry
2842            .get_ava_single_utf8(Attribute::DomainDisplayName)
2843            .map(str::to_string)
2844            .unwrap_or_else(|| format!("Kanidm {domain_name}"));
2845
2846        let domain_ldap_allow_unix_pw_bind = domain_entry
2847            .get_ava_single_bool(Attribute::LdapAllowUnixPwBind)
2848            .unwrap_or(true);
2849
2850        let domain_image = domain_entry.get_ava_single_image(Attribute::Image);
2851
2852        let domain_uuid = self.be_txn.get_db_d_uuid()?;
2853
2854        let mut_d_info = self.d_info.get_mut();
2855        mut_d_info.d_ldap_allow_unix_pw_bind = domain_ldap_allow_unix_pw_bind;
2856        if mut_d_info.d_uuid != domain_uuid {
2857            admin_warn!(
2858                "Using domain uuid from the database {} - was {} in memory",
2859                domain_name,
2860                mut_d_info.d_name,
2861            );
2862            mut_d_info.d_uuid = domain_uuid;
2863        }
2864        if mut_d_info.d_name != domain_name {
2865            admin_warn!(
2866                "Using domain name from the database {} - was {} in memory",
2867                domain_name,
2868                mut_d_info.d_name,
2869            );
2870            admin_warn!(
2871                    "If you think this is an error, see https://kanidm.github.io/kanidm/master/domain_rename.html"
2872                );
2873            mut_d_info.d_name = domain_name;
2874        }
2875        mut_d_info.d_display = display_name;
2876        mut_d_info.d_image = domain_image;
2877        Ok(())
2878    }
2879
2880    /// Reloads feature configurations if they have changed in this operation
2881    #[instrument(level = "debug", skip_all)]
2882    pub(crate) fn reload_feature_config(&mut self) -> Result<(), OperationError> {
2883        let filt = filter!(f_eq(Attribute::Class, EntryClass::Feature.into()));
2884
2885        let feature_configs = self.internal_search(filt).inspect_err(|err| {
2886            error!(?err, "reload feature configuration internal search failed",)
2887        })?;
2888
2889        let current_time = self.get_curtime();
2890        let domain_level = self.get_domain_version();
2891
2892        let mut hmac_name_history_fixup = false;
2893
2894        // TODO: How to handle disabling on a delete? Needs thought ... but also
2895        // should be impossible for someone TO delete a feature config entry?
2896
2897        for feature_entry in feature_configs {
2898            match feature_entry.get_uuid() {
2899                UUID_HMAC_NAME_FEATURE => {
2900                    if domain_level < DOMAIN_LEVEL_12 {
2901                        trace!("Skipping hmac name history config");
2902                        continue;
2903                    }
2904
2905                    let key_object = self
2906                        .get_key_providers()
2907                        .get_key_object_handle(UUID_HMAC_NAME_FEATURE)
2908                        .ok_or(OperationError::KP0079KeyObjectNotFound)?;
2909
2910                    let mut key = HmacSha256Key::default();
2911                    key_object.hkdf_s256_expand(
2912                        UUID_HMAC_NAME_FEATURE.as_bytes(),
2913                        key.as_mut_slice(),
2914                        current_time,
2915                    )?;
2916
2917                    drop(key_object);
2918
2919                    let new_feature_enabled_state = feature_entry
2920                        .get_ava_single_bool(Attribute::Enabled)
2921                        .unwrap_or_default();
2922
2923                    let feature_config_txn = &mut self.d_info.get_mut().feature_config;
2924
2925                    hmac_name_history_fixup =
2926                        !feature_config_txn.hmac_name_history.enabled && new_feature_enabled_state;
2927
2928                    feature_config_txn.hmac_name_history.enabled = new_feature_enabled_state;
2929
2930                    std::mem::swap(&mut key, &mut feature_config_txn.hmac_name_history.key);
2931                }
2932
2933                UUID_ACCOUNT_SIGNUP_FEATURE => {
2934                    if domain_level < DOMAIN_LEVEL_1_12 {
2935                        trace!("Skipping account signup config");
2936                        continue;
2937                    }
2938
2939                    let new_feature_enabled_state = feature_entry
2940                        .get_ava_single_bool(Attribute::Enabled)
2941                        .unwrap_or_default();
2942
2943                    let feature_config_txn = &mut self.d_info.get_mut().feature_config;
2944
2945                    feature_config_txn.account_signup.enabled = new_feature_enabled_state;
2946
2947                    // Probably will add flags here soon?
2948                }
2949                feature_uuid => {
2950                    error!(
2951                        ?feature_uuid,
2952                        "Unrecognised feature uuid, unable to proceed"
2953                    );
2954                    return Err(OperationError::KG004UnknownFeatureUuid);
2955                }
2956            }
2957        }
2958
2959        if hmac_name_history_fixup {
2960            plugins::hmac_name_unique::HmacNameUnique::fixup(self)?;
2961        }
2962
2963        Ok(())
2964    }
2965
2966    /// Initiate a domain display name change process. This isn't particularly scary
2967    /// because it's just a wibbly human-facing thing, not used for secure
2968    /// activities (yet)
2969    pub fn set_domain_display_name(&mut self, new_domain_name: &str) -> Result<(), OperationError> {
2970        let modl = ModifyList::new_purge_and_set(
2971            Attribute::DomainDisplayName,
2972            Value::new_utf8(new_domain_name.to_string()),
2973        );
2974        let udi = PVUUID_DOMAIN_INFO.clone();
2975        let filt = filter_all!(f_eq(Attribute::Uuid, udi));
2976        self.internal_modify(&filt, &modl)
2977    }
2978
2979    /// Initiate a domain rename process. This is generally an internal function but it's
2980    /// exposed to the cli for admins to be able to initiate the process.
2981    ///
2982    /// # Safety
2983    /// This is UNSAFE because while it may change the domain name, it doesn't update
2984    /// the running configured version of the domain name that is resident to the
2985    /// query server.
2986    ///
2987    /// Currently it's only used to test what happens if we rename the domain and how
2988    /// that impacts spns, but in the future we may need to reconsider how this is
2989    /// approached, especially if we have a domain re-name replicated to us. It could
2990    /// be that we end up needing to have this as a cow cell or similar?
2991    pub fn danger_domain_rename(&mut self, new_domain_name: &str) -> Result<(), OperationError> {
2992        let modl =
2993            ModifyList::new_purge_and_set(Attribute::DomainName, Value::new_iname(new_domain_name));
2994        let udi = PVUUID_DOMAIN_INFO.clone();
2995        let filt = filter_all!(f_eq(Attribute::Uuid, udi));
2996        self.internal_modify(&filt, &modl)
2997    }
2998
2999    pub fn reindex(&mut self, immediate: bool) -> Result<(), OperationError> {
3000        // initiate a be reindex here. This could have been from first run checking
3001        // the versions, or it could just be from the cli where an admin needs to do an
3002        // indexing.
3003        self.be_txn.reindex(immediate)
3004    }
3005
3006    fn force_schema_reload(&mut self) {
3007        self.changed_flags.insert(ChangeFlag::SCHEMA);
3008    }
3009
3010    fn force_domain_reload(&mut self) {
3011        self.changed_flags.insert(ChangeFlag::DOMAIN);
3012    }
3013
3014    pub(crate) fn upgrade_reindex(&mut self, v: i64) -> Result<(), OperationError> {
3015        self.be_txn.upgrade_reindex(v)
3016    }
3017
3018    #[inline]
3019    pub(crate) fn get_changed_app(&self) -> bool {
3020        self.changed_flags.contains(ChangeFlag::APPLICATION)
3021    }
3022
3023    #[inline]
3024    pub(crate) fn get_changed_oauth2(&self) -> bool {
3025        self.changed_flags.contains(ChangeFlag::OAUTH2)
3026    }
3027
3028    #[inline]
3029    pub(crate) fn clear_changed_oauth2(&mut self) {
3030        self.changed_flags.remove(ChangeFlag::OAUTH2)
3031    }
3032
3033    #[inline]
3034    pub(crate) fn get_changed_oauth2_client(&self) -> bool {
3035        self.changed_flags.contains(ChangeFlag::OAUTH2_CLIENT)
3036    }
3037
3038    /// Indicate that we are about to re-bootstrap this server. You should ONLY
3039    /// call this during a replication refresh!!!
3040    pub(crate) fn set_phase_bootstrap(&mut self) {
3041        *self.phase = ServerPhase::Bootstrap;
3042    }
3043
3044    /// Raise the currently running server phase.
3045    pub(crate) fn set_phase(&mut self, phase: ServerPhase) {
3046        // Phase changes are one way
3047        if phase > *self.phase {
3048            *self.phase = phase
3049        }
3050    }
3051
3052    pub(crate) fn get_phase(&mut self) -> ServerPhase {
3053        *self.phase
3054    }
3055
3056    pub(crate) fn reload(&mut self) -> Result<(), OperationError> {
3057        // First, check if the domain version has changed. This can trigger
3058        // changes to schema, access controls and more.
3059        if self.changed_flags.intersects(ChangeFlag::DOMAIN) {
3060            self.reload_domain_info_version()?;
3061        }
3062
3063        // This could be faster if we cache the set of classes changed
3064        // in an operation so we can check if we need to do the reload or not
3065        //
3066        // Reload the schema from qs.
3067        if self.changed_flags.intersects(ChangeFlag::SCHEMA) {
3068            self.reload_schema()?;
3069
3070            // If the server is in a late phase of start up or is
3071            // operational, then a reindex may be required. After the reindex, the schema
3072            // must also be reloaded so that slope optimisation indexes are loaded correctly.
3073            if *self.phase >= ServerPhase::Running {
3074                self.reindex(false)?;
3075                self.reload_schema()?;
3076            }
3077        }
3078
3079        // We need to reload cryptographic providers before anything else so that
3080        // sync agreements and the domain can access their key material.
3081        if self
3082            .changed_flags
3083            .intersects(ChangeFlag::SCHEMA | ChangeFlag::KEY_MATERIAL)
3084        {
3085            self.reload_key_material()?;
3086        }
3087
3088        // Determine if we need to update access control profiles
3089        // based on any modifications that have occurred.
3090        // IF SCHEMA CHANGED WE MUST ALSO RELOAD!!! IE if schema had an attr removed
3091        // that we rely on we MUST fail this here!!
3092        //
3093        // Also note that changing sync agreements triggers an acp reload since
3094        // access controls need to be aware of these agreements.
3095        if self
3096            .changed_flags
3097            .intersects(ChangeFlag::SCHEMA | ChangeFlag::ACP | ChangeFlag::SYNC_AGREEMENT)
3098        {
3099            self.reload_accesscontrols()?;
3100        } else {
3101            // On a reload the cache is dropped, otherwise we tell accesscontrols
3102            // to drop anything related that was changed.
3103            // self.accesscontrols
3104            //    .invalidate_related_cache(self.changed_uuid.into_inner().as_slice())
3105        }
3106
3107        if self.changed_flags.intersects(ChangeFlag::SYSTEM_CONFIG) {
3108            self.reload_system_config()?;
3109        }
3110
3111        if self.changed_flags.intersects(ChangeFlag::DOMAIN) {
3112            self.reload_domain_info()?;
3113        }
3114
3115        if self
3116            .changed_flags
3117            .intersects(ChangeFlag::FEATURE | ChangeFlag::KEY_MATERIAL)
3118        {
3119            self.reload_feature_config()?;
3120        }
3121
3122        // Clear flags
3123        self.changed_flags.remove(
3124            ChangeFlag::DOMAIN
3125                | ChangeFlag::SCHEMA
3126                | ChangeFlag::FEATURE
3127                | ChangeFlag::SYSTEM_CONFIG
3128                | ChangeFlag::ACP
3129                | ChangeFlag::SYNC_AGREEMENT
3130                | ChangeFlag::KEY_MATERIAL,
3131        );
3132
3133        Ok(())
3134    }
3135
3136    #[cfg(any(test, debug_assertions))]
3137    #[instrument(level = "debug", skip_all)]
3138    pub fn clear_cache(&mut self) -> Result<(), OperationError> {
3139        self.be_txn.clear_cache()
3140    }
3141
3142    #[instrument(level = "debug", name="qswt_commit" skip_all)]
3143    pub fn commit(mut self) -> Result<(), OperationError> {
3144        self.reload()?;
3145
3146        // Now destructure the transaction ready to reset it.
3147        let QueryServerWriteTransaction {
3148            committed,
3149            phase,
3150            d_info,
3151            system_config,
3152            mut be_txn,
3153            schema,
3154            accesscontrols,
3155            cid,
3156            dyngroup_cache,
3157            key_providers,
3158            // Hold these for a bit more ...
3159            _db_ticket,
3160            _write_ticket,
3161            // Ignore values that don't need a commit.
3162            curtime: _,
3163            trim_cid: _,
3164            changed_flags,
3165            changed_uuid: _,
3166            resolve_filter_cache: _,
3167            resolve_filter_cache_clear,
3168            mut resolve_filter_cache_write,
3169            txn_name_to_uuid: _,
3170        } = self;
3171        debug_assert!(!committed);
3172
3173        // Should have been cleared by any reloads.
3174        trace!(
3175            changed = ?changed_flags.iter_names().collect::<Vec<_>>(),
3176        );
3177
3178        // Write the cid to the db. If this fails, we can't assume replication
3179        // will be stable, so return if it fails.
3180        be_txn.set_db_ts_max(cid.ts)?;
3181        cid.commit();
3182
3183        // We don't care if this passes/fails, committing this is fine.
3184        if resolve_filter_cache_clear {
3185            resolve_filter_cache_write.clear();
3186        }
3187        resolve_filter_cache_write.commit();
3188
3189        // Point of no return - everything has been validated and reloaded.
3190        //
3191        // = Lets commit =
3192        schema
3193            .commit()
3194            .map(|_| d_info.commit())
3195            .map(|_| system_config.commit())
3196            .map(|_| phase.commit())
3197            .map(|_| dyngroup_cache.commit())
3198            .and_then(|_| key_providers.commit())
3199            .and_then(|_| accesscontrols.commit())
3200            .and_then(|_| be_txn.commit())
3201    }
3202
3203    pub(crate) fn get_txn_cid(&self) -> &Cid {
3204        &self.cid
3205    }
3206}
3207
3208#[cfg(test)]
3209mod tests {
3210    use crate::prelude::*;
3211    use kanidm_proto::scim_v1::{
3212        server::{ScimListResponse, ScimReference},
3213        JsonValue, ScimEntryGetQuery, ScimFilter,
3214    };
3215    use std::num::NonZeroU64;
3216
3217    #[qs_test]
3218    async fn test_name_to_uuid(server: &QueryServer) {
3219        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3220
3221        let t_uuid = Uuid::new_v4();
3222        assert!(server_txn
3223            .internal_create(vec![entry_init!(
3224                (Attribute::Class, EntryClass::Object.to_value()),
3225                (Attribute::Class, EntryClass::Account.to_value()),
3226                (Attribute::Class, EntryClass::Person.to_value()),
3227                (Attribute::Name, Value::new_iname("testperson1")),
3228                (Attribute::Uuid, Value::Uuid(t_uuid)),
3229                (Attribute::Description, Value::new_utf8s("testperson1")),
3230                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
3231            ),])
3232            .is_ok());
3233
3234        // Name doesn't exist
3235        let r1 = server_txn.name_to_uuid("testpers");
3236        assert!(r1.is_err());
3237        // Name doesn't exist (not syntax normalised)
3238        let r2 = server_txn.name_to_uuid("tEsTpErS");
3239        assert!(r2.is_err());
3240        // Name does exist
3241        let r3 = server_txn.name_to_uuid("testperson1");
3242        assert_eq!(r3, Ok(t_uuid));
3243        // Name is not syntax normalised (but exists)
3244        let r4 = server_txn.name_to_uuid("tEsTpErSoN1");
3245        assert_eq!(r4, Ok(t_uuid));
3246        // Name is an rdn
3247        let r5 = server_txn.name_to_uuid("name=testperson1");
3248        assert_eq!(r5, Ok(t_uuid));
3249        // Name is a dn
3250        let r6 = server_txn.name_to_uuid("name=testperson1,o=example");
3251        assert_eq!(r6, Ok(t_uuid));
3252    }
3253
3254    #[qs_test]
3255    async fn test_external_id_to_uuid(server: &QueryServer) {
3256        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3257
3258        let t_uuid = Uuid::new_v4();
3259        assert!(server_txn
3260            .internal_create(vec![entry_init!(
3261                (Attribute::Class, EntryClass::Object.to_value()),
3262                (Attribute::Class, EntryClass::ExtensibleObject.to_value()),
3263                (Attribute::Uuid, Value::Uuid(t_uuid)),
3264                (
3265                    Attribute::SyncExternalId,
3266                    Value::new_iutf8("uid=testperson")
3267                )
3268            ),])
3269            .is_ok());
3270
3271        // Name doesn't exist
3272        let r1 = server_txn.sync_external_id_to_uuid("tobias");
3273        assert_eq!(r1, Ok(None));
3274        // Name doesn't exist (not syntax normalised)
3275        let r2 = server_txn.sync_external_id_to_uuid("tObIAs");
3276        assert_eq!(r2, Ok(None));
3277        // Name does exist
3278        let r3 = server_txn.sync_external_id_to_uuid("uid=testperson");
3279        assert_eq!(r3, Ok(Some(t_uuid)));
3280        // Name is not syntax normalised (but exists)
3281        let r4 = server_txn.sync_external_id_to_uuid("uId=TeStPeRsOn");
3282        assert_eq!(r4, Ok(Some(t_uuid)));
3283    }
3284
3285    #[qs_test]
3286    async fn test_uuid_to_spn(server: &QueryServer) {
3287        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3288
3289        let e1 = entry_init!(
3290            (Attribute::Class, EntryClass::Object.to_value()),
3291            (Attribute::Class, EntryClass::Person.to_value()),
3292            (Attribute::Class, EntryClass::Account.to_value()),
3293            (Attribute::Name, Value::new_iname("testperson1")),
3294            (
3295                Attribute::Uuid,
3296                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3297            ),
3298            (Attribute::Description, Value::new_utf8s("testperson1")),
3299            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
3300        );
3301        let ce = CreateEvent::new_internal(vec![e1]);
3302        let cr = server_txn.create(&ce);
3303        assert!(cr.is_ok());
3304
3305        // Name doesn't exist
3306        let r1 = server_txn.uuid_to_spn(uuid!("bae3f507-e6c3-44ba-ad01-f8ff1083534a"));
3307        // There is nothing.
3308        assert_eq!(r1, Ok(None));
3309        // Name does exist
3310        let r3 = server_txn.uuid_to_spn(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"));
3311        println!("{r3:?}");
3312        assert_eq!(
3313            r3.unwrap().unwrap(),
3314            Value::new_spn_str("testperson1", "example.com")
3315        );
3316        // Name is not syntax normalised (but exists)
3317        let r4 = server_txn.uuid_to_spn(uuid!("CC8E95B4-C24F-4D68-BA54-8BED76F63930"));
3318        assert_eq!(
3319            r4.unwrap().unwrap(),
3320            Value::new_spn_str("testperson1", "example.com")
3321        );
3322    }
3323
3324    #[qs_test]
3325    async fn test_uuid_to_rdn(server: &QueryServer) {
3326        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3327
3328        let e1 = entry_init!(
3329            (Attribute::Class, EntryClass::Object.to_value()),
3330            (Attribute::Class, EntryClass::Person.to_value()),
3331            (Attribute::Class, EntryClass::Account.to_value()),
3332            (Attribute::Name, Value::new_iname("testperson1")),
3333            (
3334                Attribute::Uuid,
3335                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3336            ),
3337            (Attribute::Description, Value::new_utf8s("testperson")),
3338            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
3339        );
3340        let ce = CreateEvent::new_internal(vec![e1]);
3341        let cr = server_txn.create(&ce);
3342        assert!(cr.is_ok());
3343
3344        // Name doesn't exist
3345        let r1 = server_txn.uuid_to_rdn(uuid!("bae3f507-e6c3-44ba-ad01-f8ff1083534a"));
3346        // There is nothing.
3347        assert_eq!(r1.unwrap(), "uuid=bae3f507-e6c3-44ba-ad01-f8ff1083534a");
3348        // Name does exist
3349        let r3 = server_txn.uuid_to_rdn(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"));
3350        println!("{r3:?}");
3351        assert_eq!(r3.unwrap(), "spn=testperson1@example.com");
3352        // Uuid is not syntax normalised (but exists)
3353        let r4 = server_txn.uuid_to_rdn(uuid!("CC8E95B4-C24F-4D68-BA54-8BED76F63930"));
3354        assert_eq!(r4.unwrap(), "spn=testperson1@example.com");
3355    }
3356
3357    #[qs_test]
3358    async fn test_clone_value(server: &QueryServer) {
3359        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3360        let e1 = entry_init!(
3361            (Attribute::Class, EntryClass::Object.to_value()),
3362            (Attribute::Class, EntryClass::Account.to_value()),
3363            (Attribute::Class, EntryClass::Person.to_value()),
3364            (Attribute::Name, Value::new_iname("testperson1")),
3365            (
3366                Attribute::Uuid,
3367                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3368            ),
3369            (Attribute::Description, Value::new_utf8s("testperson1")),
3370            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
3371        );
3372        let ce = CreateEvent::new_internal(vec![e1]);
3373        let cr = server_txn.create(&ce);
3374        assert!(cr.is_ok());
3375
3376        // test attr not exist
3377        let r1 = server_txn.clone_value(&Attribute::from("tausau"), "naoeutnhaou");
3378
3379        assert!(r1.is_err());
3380
3381        // test attr not-normalised (error)
3382        // test attr not-reference
3383        let r2 = server_txn.clone_value(&Attribute::Custom("NaMe".into()), "NaMe");
3384
3385        assert!(r2.is_err());
3386
3387        // test attr reference
3388        let r3 = server_txn.clone_value(&Attribute::from("member"), "testperson1");
3389
3390        assert_eq!(
3391            r3,
3392            Ok(Value::ReferN(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930")))
3393        );
3394
3395        // test attr reference already resolved.
3396        let r4 = server_txn.clone_value(
3397            &Attribute::from("member"),
3398            "cc8e95b4-c24f-4d68-ba54-8bed76f63930",
3399        );
3400
3401        debug!("{:?}", r4);
3402        assert_eq!(
3403            r4,
3404            Ok(Value::ReferN(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930")))
3405        );
3406    }
3407
3408    #[qs_test(domain_level=DOMAIN_LEVEL_13)]
3409    async fn test_dynamic_schema_class(server: &QueryServer) {
3410        let e1 = entry_init!(
3411            (Attribute::Class, EntryClass::Object.to_value()),
3412            (Attribute::Class, EntryClass::TestClass.to_value()),
3413            (Attribute::Name, Value::new_iname("testobj1")),
3414            (
3415                Attribute::Uuid,
3416                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3417            )
3418        );
3419
3420        // Class definition
3421        let e_cd = entry_init!(
3422            (Attribute::Class, EntryClass::Object.to_value()),
3423            (Attribute::Class, EntryClass::ClassType.to_value()),
3424            (
3425                Attribute::ClassName,
3426                Value::new_iutf8(EntryClass::TestClass.as_str())
3427            ),
3428            (
3429                Attribute::Uuid,
3430                Value::Uuid(uuid!("cfcae205-31c3-484b-8ced-667d1709c5e3"))
3431            ),
3432            (Attribute::Description, Value::new_utf8s("Test Class")),
3433            (Attribute::May, Value::new_iutf8n(Attribute::Name.as_str()))
3434        );
3435        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3436        // Add a new class.
3437        let ce_class = CreateEvent::new_internal(vec![e_cd.clone()]);
3438        assert!(server_txn.create(&ce_class).is_ok());
3439        // Trying to add it now should fail.
3440        let ce_fail = CreateEvent::new_internal(vec![e1.clone()]);
3441        assert!(server_txn.create(&ce_fail).is_err());
3442
3443        // Commit
3444        server_txn.commit().expect("should not fail");
3445
3446        // Start a new write
3447        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3448        // Add the class to an object
3449        // should work
3450        let ce_work = CreateEvent::new_internal(vec![e1.clone()]);
3451        assert!(server_txn.create(&ce_work).is_ok());
3452
3453        // Commit
3454        server_txn.commit().expect("should not fail");
3455
3456        // Start a new write
3457        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3458        // delete the class
3459        let de_class = DeleteEvent::new_internal_invalid(filter!(f_eq(
3460            Attribute::ClassName,
3461            EntryClass::TestClass.into()
3462        )));
3463        assert!(server_txn.delete(&de_class).is_ok());
3464        // Commit
3465        server_txn.commit().expect("should not fail");
3466
3467        // Start a new write
3468        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3469        // Trying to add now should fail
3470        let ce_fail = CreateEvent::new_internal(vec![e1.clone()]);
3471        assert!(server_txn.create(&ce_fail).is_err());
3472        // Search our entry
3473        let testobj1 = server_txn
3474            .internal_search_uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3475            .expect("failed");
3476        assert!(testobj1.attribute_equality(Attribute::Class, &EntryClass::TestClass.into()));
3477
3478        // Should still be good
3479        server_txn.commit().expect("should not fail");
3480        // Commit.
3481    }
3482
3483    #[qs_test(domain_level=DOMAIN_LEVEL_13)]
3484    async fn test_dynamic_schema_attr(server: &QueryServer) {
3485        let e1 = entry_init!(
3486            (Attribute::Class, EntryClass::Object.to_value()),
3487            (Attribute::Class, EntryClass::ExtensibleObject.to_value()),
3488            (Attribute::Name, Value::new_iname("testobj1")),
3489            (
3490                Attribute::Uuid,
3491                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3492            ),
3493            (Attribute::TestAttr, Value::new_utf8s("test"))
3494        );
3495
3496        // Attribute definition
3497        let e_ad = entry_init!(
3498            (Attribute::Class, EntryClass::Object.to_value()),
3499            (Attribute::Class, EntryClass::AttributeType.to_value()),
3500            (
3501                Attribute::Uuid,
3502                Value::Uuid(uuid!("cfcae205-31c3-484b-8ced-667d1709c5e3"))
3503            ),
3504            (
3505                Attribute::AttributeName,
3506                Value::new_iutf8(Attribute::TestAttr.as_str())
3507            ),
3508            (Attribute::Description, Value::new_utf8s("Test Attribute")),
3509            (Attribute::MultiValue, Value::new_bool(false)),
3510            (Attribute::Unique, Value::new_bool(false)),
3511            (
3512                Attribute::Syntax,
3513                Value::new_syntaxs("UTF8STRING").expect("syntax")
3514            )
3515        );
3516
3517        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3518        // Add a new attribute.
3519        let ce_attr = CreateEvent::new_internal(vec![e_ad.clone()]);
3520        assert!(server_txn.create(&ce_attr).is_ok());
3521        // Trying to add it now should fail. (use extensible object)
3522        let ce_fail = CreateEvent::new_internal(vec![e1.clone()]);
3523        assert!(server_txn.create(&ce_fail).is_err());
3524
3525        // Commit
3526        server_txn.commit().expect("should not fail");
3527
3528        // Start a new write
3529        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3530        // Add the attr to an object
3531        // should work
3532        let ce_work = CreateEvent::new_internal(vec![e1.clone()]);
3533        assert!(server_txn.create(&ce_work).is_ok());
3534
3535        // Commit
3536        server_txn.commit().expect("should not fail");
3537
3538        // Start a new write
3539        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3540        // delete the attr
3541        let de_attr = DeleteEvent::new_internal_invalid(filter!(f_eq(
3542            Attribute::AttributeName,
3543            PartialValue::from(Attribute::TestAttr)
3544        )));
3545        assert!(server_txn.delete(&de_attr).is_ok());
3546        // Commit
3547        server_txn.commit().expect("should not fail");
3548
3549        // Start a new write
3550        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3551        // Trying to add now should fail
3552        let ce_fail = CreateEvent::new_internal(vec![e1.clone()]);
3553        assert!(server_txn.create(&ce_fail).is_err());
3554        // Search our attribute - should FAIL
3555        let filt = filter!(f_eq(Attribute::TestAttr, PartialValue::new_utf8s("test")));
3556        assert!(server_txn.internal_search(filt).is_err());
3557        // Search the entry - the attribute will still be present
3558        // even if we can't search on it.
3559        let testobj1 = server_txn
3560            .internal_search_uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
3561            .expect("failed");
3562        assert!(testobj1.attribute_equality(Attribute::TestAttr, &PartialValue::new_utf8s("test")));
3563
3564        server_txn.commit().expect("should not fail");
3565        // Commit.
3566    }
3567
3568    #[qs_test]
3569    async fn test_scim_entry_structure(server: &QueryServer) {
3570        let mut read_txn = server.read().await.unwrap();
3571
3572        // Query entry (A builtin one ?)
3573        let entry = read_txn
3574            .internal_search_uuid(UUID_IDM_PEOPLE_SELF_NAME_WRITE)
3575            .unwrap();
3576
3577        // Convert entry into scim
3578        let reduced = entry.as_ref().clone().into_reduced();
3579        let scim_entry = reduced.to_scim_kanidm(&mut read_txn).unwrap();
3580
3581        // Assert scim entry attributes are as expected
3582        assert_eq!(scim_entry.header.id, UUID_IDM_PEOPLE_SELF_NAME_WRITE);
3583        let name_scim = scim_entry.attrs.get(&Attribute::Name).unwrap();
3584        match name_scim {
3585            ScimValueKanidm::String(name) => {
3586                assert_eq!(name.clone(), "idm_people_self_name_write")
3587            }
3588            _ => {
3589                panic!("expected String, actual {name_scim:?}");
3590            }
3591        }
3592
3593        // such as returning a new struct type for `members` attributes or `managed_by`
3594        let entry_managed_by_scim = scim_entry.attrs.get(&Attribute::EntryManagedBy).unwrap();
3595        match entry_managed_by_scim {
3596            ScimValueKanidm::EntryReference(managed_by) => {
3597                assert_eq!(
3598                    managed_by.clone(),
3599                    ScimReference {
3600                        uuid: UUID_IDM_ADMINS,
3601                        value: "idm_admins@example.com".to_string()
3602                    }
3603                )
3604            }
3605            _ => {
3606                panic!("expected EntryReference, actual {entry_managed_by_scim:?}");
3607            }
3608        }
3609
3610        let members_scim = scim_entry.attrs.get(&Attribute::Member).unwrap();
3611        match members_scim {
3612            ScimValueKanidm::EntryReferences(members) => {
3613                assert_eq!(
3614                    members.first().unwrap().clone(),
3615                    ScimReference {
3616                        uuid: UUID_IDM_ALL_PERSONS,
3617                        value: "idm_all_persons@example.com".to_string()
3618                    }
3619                )
3620            }
3621            _ => {
3622                panic!("expected EntryReferences, actual {members_scim:?}");
3623            }
3624        }
3625    }
3626
3627    #[qs_test]
3628    async fn test_scim_effective_access_query(server: &QueryServer) {
3629        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3630
3631        let group_uuid = Uuid::new_v4();
3632        let e1 = entry_init!(
3633            (Attribute::Class, EntryClass::Object.to_value()),
3634            (Attribute::Class, EntryClass::Group.to_value()),
3635            (Attribute::Name, Value::new_iname("testgroup")),
3636            (Attribute::Uuid, Value::Uuid(group_uuid))
3637        );
3638
3639        assert!(server_txn.internal_create(vec![e1]).is_ok());
3640        assert!(server_txn.commit().is_ok());
3641
3642        // Now read that entry.
3643
3644        let mut server_txn = server.read().await.unwrap();
3645
3646        let idm_admin_entry = server_txn.internal_search_uuid(UUID_IDM_ADMIN).unwrap();
3647        let idm_admin_ident = Identity::from_impersonate_entry_readwrite(idm_admin_entry);
3648
3649        let query = ScimEntryGetQuery {
3650            ext_access_check: true,
3651            ..Default::default()
3652        };
3653
3654        let scim_entry = server_txn
3655            .scim_entry_id_get_ext(group_uuid, EntryClass::Group, query, idm_admin_ident)
3656            .unwrap();
3657
3658        let ext_access_check = scim_entry.ext_access_check.unwrap();
3659
3660        trace!(?ext_access_check);
3661
3662        assert!(ext_access_check.delete);
3663        assert!(ext_access_check.search.check(&Attribute::DirectMemberOf));
3664        assert!(ext_access_check.search.check(&Attribute::MemberOf));
3665        assert!(ext_access_check.search.check(&Attribute::Name));
3666        assert!(ext_access_check.modify_present.check(&Attribute::Name));
3667        assert!(ext_access_check.modify_remove.check(&Attribute::Name));
3668    }
3669
3670    #[qs_test]
3671    async fn test_scim_basic_search_ext_query(server: &QueryServer) {
3672        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3673
3674        let group_uuid = Uuid::new_v4();
3675        let e1 = entry_init!(
3676            (Attribute::Class, EntryClass::Object.to_value()),
3677            (Attribute::Class, EntryClass::Group.to_value()),
3678            (Attribute::Name, Value::new_iname("testgroup")),
3679            (Attribute::Uuid, Value::Uuid(group_uuid))
3680        );
3681
3682        assert!(server_txn.internal_create(vec![e1]).is_ok());
3683        assert!(server_txn.commit().is_ok());
3684
3685        // Now read that entry.
3686        let mut server_txn = server.read().await.unwrap();
3687
3688        let idm_admin_entry = server_txn.internal_search_uuid(UUID_IDM_ADMIN).unwrap();
3689        let idm_admin_ident = Identity::from_impersonate_entry_readwrite(idm_admin_entry);
3690
3691        let filter = ScimFilter::And(
3692            Box::new(ScimFilter::Equal(
3693                Attribute::Class.into(),
3694                EntryClass::Group.into(),
3695            )),
3696            Box::new(ScimFilter::Equal(
3697                Attribute::Uuid.into(),
3698                JsonValue::String(group_uuid.to_string()),
3699            )),
3700        );
3701
3702        let base: ScimListResponse = server_txn
3703            .scim_search_ext(idm_admin_ident, filter, ScimEntryGetQuery::default())
3704            .unwrap();
3705
3706        assert_eq!(base.resources.len(), 1);
3707        assert_eq!(base.total_results, 1);
3708        // Pagination not requested,
3709        assert_eq!(base.items_per_page, None);
3710        assert_eq!(base.start_index, None);
3711        assert_eq!(base.resources[0].header.id, group_uuid);
3712    }
3713
3714    #[qs_test]
3715    async fn test_scim_basic_search_ext_query_with_sort(server: &QueryServer) {
3716        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
3717
3718        for i in (1..4).rev() {
3719            let e1 = entry_init!(
3720                (Attribute::Class, EntryClass::Object.to_value()),
3721                (Attribute::Class, EntryClass::Group.to_value()),
3722                (
3723                    Attribute::Name,
3724                    Value::new_iname(format!("testgroup{i}").as_str())
3725                )
3726            );
3727            assert!(server_txn.internal_create(vec![e1]).is_ok());
3728        }
3729
3730        assert!(server_txn.commit().is_ok());
3731
3732        // Now read that entry.
3733        let mut server_txn = server.read().await.unwrap();
3734
3735        let idm_admin_entry = server_txn.internal_search_uuid(UUID_IDM_ADMIN).unwrap();
3736        let idm_admin_ident = Identity::from_impersonate_entry_readwrite(idm_admin_entry);
3737
3738        let filter = ScimFilter::And(
3739            Box::new(ScimFilter::Equal(
3740                Attribute::Class.into(),
3741                EntryClass::Group.into(),
3742            )),
3743            Box::new(ScimFilter::StartsWith(
3744                Attribute::Name.into(),
3745                JsonValue::String("testgroup".into()),
3746            )),
3747        );
3748
3749        let base: ScimListResponse = server_txn
3750            .scim_search_ext(
3751                idm_admin_ident.clone(),
3752                filter.clone(),
3753                ScimEntryGetQuery {
3754                    sort_by: Some(Attribute::Name),
3755                    ..Default::default()
3756                },
3757            )
3758            .unwrap();
3759
3760        assert_eq!(base.resources.len(), 3);
3761        assert_eq!(base.total_results, 3);
3762        // Pagination not requested,
3763        assert_eq!(base.items_per_page, None);
3764        assert_eq!(base.start_index, None);
3765
3766        let Some(ScimValueKanidm::String(testgroup_name_0)) =
3767            base.resources[0].attrs.get(&Attribute::Name)
3768        else {
3769            panic!("Invalid data in attribute.");
3770        };
3771        let Some(ScimValueKanidm::String(testgroup_name_1)) =
3772            base.resources[1].attrs.get(&Attribute::Name)
3773        else {
3774            panic!("Invalid data in attribute.");
3775        };
3776        let Some(ScimValueKanidm::String(testgroup_name_2)) =
3777            base.resources[2].attrs.get(&Attribute::Name)
3778        else {
3779            panic!("Invalid data in attribute.");
3780        };
3781
3782        assert!(testgroup_name_0 < testgroup_name_1);
3783        assert!(testgroup_name_0 < testgroup_name_2);
3784        assert!(testgroup_name_1 < testgroup_name_2);
3785
3786        // ================
3787        // Test pagination.
3788        let base: ScimListResponse = server_txn
3789            .scim_search_ext(
3790                idm_admin_ident.clone(),
3791                filter.clone(),
3792                ScimEntryGetQuery {
3793                    count: NonZeroU64::new(1),
3794                    ..Default::default()
3795                },
3796            )
3797            .unwrap();
3798
3799        assert_eq!(base.resources.len(), 1);
3800        assert_eq!(base.total_results, 3);
3801        // Pagination not requested,
3802        assert_eq!(base.items_per_page, NonZeroU64::new(1));
3803        assert_eq!(base.start_index, NonZeroU64::new(1));
3804
3805        let Some(ScimValueKanidm::String(testgroup_name_0)) =
3806            base.resources[0].attrs.get(&Attribute::Name)
3807        else {
3808            panic!("Invalid data in attribute.");
3809        };
3810        // DB has reverse order
3811        assert_eq!(testgroup_name_0, "testgroup3");
3812
3813        // ================
3814        // Test pagination + sort
3815        let base: ScimListResponse = server_txn
3816            .scim_search_ext(
3817                idm_admin_ident,
3818                filter.clone(),
3819                ScimEntryGetQuery {
3820                    sort_by: Some(Attribute::Name),
3821                    count: NonZeroU64::new(2),
3822                    start_index: NonZeroU64::new(2),
3823                    ..Default::default()
3824                },
3825            )
3826            .unwrap();
3827
3828        assert_eq!(base.resources.len(), 2);
3829        assert_eq!(base.total_results, 3);
3830        assert_eq!(base.items_per_page, NonZeroU64::new(2));
3831        assert_eq!(base.start_index, NonZeroU64::new(2));
3832
3833        let Some(ScimValueKanidm::String(testgroup_name_0)) =
3834            base.resources[0].attrs.get(&Attribute::Name)
3835        else {
3836            panic!("Invalid data in attribute.");
3837        };
3838        let Some(ScimValueKanidm::String(testgroup_name_1)) =
3839            base.resources[1].attrs.get(&Attribute::Name)
3840        else {
3841            panic!("Invalid data in attribute.");
3842        };
3843        // Sorted, note we skipped entry "testgroup 1" using pagination.
3844        assert_eq!(testgroup_name_0, "testgroup2");
3845        assert_eq!(testgroup_name_1, "testgroup3");
3846    }
3847}