Skip to main content

kanidmd_lib/
modify.rs

1//! Modification expressions and validation. This is how `ModifyEvents` store and
2//! express the series of Modifications that should be applied. These are expressed
3//! as "states" on what attribute-values should appear as within the `Entry`
4
5use std::slice;
6
7use kanidm_proto::{
8    internal::{Modify as ProtoModify, ModifyList as ProtoModifyList, OperationError, SchemaError},
9    v1::Entry as ProtoEntry,
10};
11// Should this be std?
12use serde::{Deserialize, Serialize};
13use std::collections::BTreeMap;
14
15use crate::{
16    prelude::*,
17    schema::SchemaTransaction,
18    value::{PartialValue, Value},
19};
20
21#[derive(Serialize, Deserialize, Debug, Clone)]
22pub struct ModifyValid;
23#[derive(Serialize, Deserialize, Debug, Clone)]
24pub struct ModifyInvalid;
25
26#[derive(Debug, Clone)]
27#[allow(clippy::large_enum_variant)]
28pub enum Modify {
29    /// This value *should* exist for this attribute.
30    Present(Attribute, Value),
31    /// This value *should not* exist for this attribute.
32    Removed(Attribute, PartialValue),
33    /// This attr should not exist, and if it does exist, will have all content removed.
34    Purged(Attribute),
35    /// This attr and value must exist *in this state* for this change to proceed.
36    Assert(Attribute, PartialValue),
37    /// Set and replace the entire content of an attribute. This requires both presence
38    /// and removal access to the attribute to proceed.
39    Set(Attribute, ValueSet),
40}
41
42pub fn m_pres(attr: Attribute, v: &Value) -> Modify {
43    Modify::Present(attr, v.clone())
44}
45
46pub fn m_remove(attr: Attribute, v: &PartialValue) -> Modify {
47    Modify::Removed(attr, v.clone())
48}
49
50pub fn m_purge(attr: Attribute) -> Modify {
51    Modify::Purged(attr)
52}
53
54pub fn m_assert(attr: Attribute, v: &PartialValue) -> Modify {
55    Modify::Assert(attr, v.clone())
56}
57
58impl Modify {
59    pub fn from(
60        m: &ProtoModify,
61        qs: &mut QueryServerWriteTransaction,
62    ) -> Result<Self, OperationError> {
63        Ok(match m {
64            ProtoModify::Present(a, v) => {
65                let a = Attribute::from(a.as_str());
66                let v = qs.clone_value(&a, v)?;
67                Modify::Present(a, v)
68            }
69            ProtoModify::Removed(a, v) => {
70                let a = Attribute::from(a.as_str());
71                let v = qs.clone_partialvalue(&a, v)?;
72                Modify::Removed(a, v)
73            }
74            ProtoModify::Purged(a) => Modify::Purged(Attribute::from(a.as_str())),
75        })
76    }
77}
78
79#[derive(Clone, Debug, Default)]
80pub struct ModifyList<VALID> {
81    // This is never read, it's just used for state machine enforcement.
82    #[allow(dead_code)]
83    valid: VALID,
84    // The order of this list matters. Each change must be done in order.
85    mods: Vec<Modify>,
86}
87
88impl<'a> IntoIterator for &'a ModifyList<ModifyValid> {
89    type IntoIter = slice::Iter<'a, Modify>;
90    type Item = &'a Modify;
91
92    fn into_iter(self) -> Self::IntoIter {
93        self.mods.iter()
94    }
95}
96
97impl ModifyList<ModifyInvalid> {
98    pub fn new() -> Self {
99        ModifyList {
100            valid: ModifyInvalid,
101            mods: Vec::with_capacity(0),
102        }
103    }
104
105    pub fn new_list(mods: Vec<Modify>) -> Self {
106        ModifyList {
107            valid: ModifyInvalid,
108            mods,
109        }
110    }
111
112    pub fn new_purge_and_set(attr: Attribute, v: Value) -> Self {
113        Self::new_list(vec![m_purge(attr.clone()), Modify::Present(attr, v)])
114    }
115
116    pub fn new_append(attr: Attribute, v: Value) -> Self {
117        Self::new_list(vec![Modify::Present(attr, v)])
118    }
119
120    pub fn new_remove(attr: Attribute, pv: PartialValue) -> Self {
121        Self::new_list(vec![Modify::Removed(attr, pv)])
122    }
123
124    pub fn new_purge(attr: Attribute) -> Self {
125        Self::new_list(vec![m_purge(attr)])
126    }
127
128    pub fn new_set(attr: Attribute, vs: ValueSet) -> Self {
129        Self::new_list(vec![Modify::Set(attr, vs)])
130    }
131
132    pub fn push_mod(&mut self, modify: Modify) {
133        self.mods.push(modify)
134    }
135
136    pub fn from(
137        ml: &ProtoModifyList,
138        qs: &mut QueryServerWriteTransaction,
139    ) -> Result<Self, OperationError> {
140        // For each ProtoModify, do a from.
141        let inner: Result<Vec<_>, _> = ml.mods.iter().map(|pm| Modify::from(pm, qs)).collect();
142        match inner {
143            Ok(m) => Ok(ModifyList {
144                valid: ModifyInvalid,
145                mods: m,
146            }),
147            Err(e) => Err(e),
148        }
149    }
150
151    pub fn from_patch(
152        pe: &ProtoEntry,
153        qs: &mut QueryServerWriteTransaction,
154    ) -> Result<Self, OperationError> {
155        let mut mods = Vec::with_capacity(0);
156
157        pe.attrs.iter().try_for_each(|(attr, vals)| {
158            // Issue a purge to the attr.
159            let attr: Attribute = attr.as_str().into();
160            mods.push(m_purge(attr.clone()));
161            // Now if there are vals, push those too.
162            // For each value we want to now be present.
163            vals.iter().try_for_each(|val| {
164                qs.clone_value(&attr, val).map(|resolved_v| {
165                    mods.push(Modify::Present(attr.clone(), resolved_v));
166                })
167            })
168        })?;
169        Ok(ModifyList {
170            valid: ModifyInvalid,
171            mods,
172        })
173    }
174
175    pub fn validate(
176        &self,
177        schema: &dyn SchemaTransaction,
178    ) -> Result<ModifyList<ModifyValid>, SchemaError> {
179        let schema_attributes = schema.get_attributes();
180        /*
181        let schema_name = schema_attributes
182            .get(Attribute::Name.as_ref()")
183            .expect("Critical: Core schema corrupt or missing. To initiate a core transfer, please deposit substitute core in receptacle.");
184        */
185
186        let res: Result<Vec<Modify>, _> = self
187            .mods
188            .iter()
189            .map(|m| match m {
190                Modify::Present(attr, value) => match schema_attributes.get(attr) {
191                    Some(schema_a) => schema_a
192                        .validate_value(attr, value)
193                        .map(|_| Modify::Present(attr.clone(), value.clone())),
194                    None => Err(SchemaError::InvalidAttribute(attr.to_string())),
195                },
196                Modify::Removed(attr, value) => match schema_attributes.get(attr) {
197                    Some(schema_a) => schema_a
198                        .validate_partialvalue(attr, value)
199                        .map(|_| Modify::Removed(attr.clone(), value.clone())),
200                    None => Err(SchemaError::InvalidAttribute(attr.to_string())),
201                },
202                Modify::Assert(attr, value) => match schema_attributes.get(attr) {
203                    Some(schema_a) => schema_a
204                        .validate_partialvalue(attr, value)
205                        .map(|_| Modify::Assert(attr.clone(), value.clone())),
206                    None => Err(SchemaError::InvalidAttribute(attr.to_string())),
207                },
208                Modify::Purged(attr) => match schema_attributes.get(attr) {
209                    Some(_attr_name) => Ok(Modify::Purged(attr.clone())),
210                    None => Err(SchemaError::InvalidAttribute(attr.to_string())),
211                },
212                Modify::Set(attr, valueset) => match schema_attributes.get(attr) {
213                    Some(_attr_name) => Ok(Modify::Set(attr.clone(), valueset.clone())),
214                    None => Err(SchemaError::InvalidAttribute(attr.to_string())),
215                },
216            })
217            .collect();
218
219        let valid_mods = res?;
220
221        // Return new ModifyList!
222        Ok(ModifyList {
223            valid: ModifyValid,
224            mods: valid_mods,
225        })
226    }
227
228    /// ⚠️  - Convert a modlist to be considered valid, bypassing schema.
229    /// This is a TEST ONLY method and will never be exposed in production.
230    #[cfg(test)]
231    pub(crate) fn into_valid(self) -> ModifyList<ModifyValid> {
232        ModifyList {
233            valid: ModifyValid,
234            mods: self.mods,
235        }
236    }
237}
238
239impl FromIterator<(Attribute, Option<ValueSet>)> for ModifyList<ModifyInvalid> {
240    fn from_iter<I: IntoIterator<Item = (Attribute, Option<ValueSet>)>>(iter: I) -> Self {
241        let mods = iter
242            .into_iter()
243            .map(|(attr, maybe_valueset)| {
244                if let Some(valueset) = maybe_valueset {
245                    Modify::Set(attr, valueset)
246                } else {
247                    Modify::Purged(attr)
248                }
249            })
250            .collect();
251
252        ModifyList {
253            valid: ModifyInvalid,
254            mods,
255        }
256    }
257}
258
259impl From<BTreeMap<Attribute, Option<ValueSet>>> for ModifyList<ModifyInvalid> {
260    fn from(attrs: BTreeMap<Attribute, Option<ValueSet>>) -> Self {
261        Self::from_iter(attrs)
262    }
263}
264
265impl ModifyList<ModifyValid> {
266    /// ⚠️  - Create a new modlist that is considered valid, bypassing schema.
267    /// This is a TEST ONLY method and will never be exposed in production.
268    #[cfg(test)]
269    pub fn new_valid_list(mods: Vec<Modify>) -> Self {
270        ModifyList {
271            valid: ModifyValid,
272            mods,
273        }
274    }
275
276    pub fn iter(&self) -> slice::Iter<'_, Modify> {
277        self.mods.iter()
278    }
279}
280
281impl<VALID> ModifyList<VALID> {
282    pub fn len(&self) -> usize {
283        self.mods.len()
284    }
285
286    pub fn is_empty(&self) -> bool {
287        self.len() == 0
288    }
289}