kanidmd_lib/valueset/
apppwd.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use crate::be::dbvalue::{DbValueApplicationPassword, DbValueSetV2};
use crate::credential::{apppwd::ApplicationPassword, Password};
use crate::prelude::*;
use crate::schema::SchemaAttribute;
use crate::valueset::ScimResolveStatus;
use std::collections::BTreeMap;

use kanidm_proto::scim_v1::server::ScimApplicationPassword;

#[derive(Debug, Clone)]
pub struct ValueSetApplicationPassword {
    // The map key is application's UUID
    // The value is a vector instead of BTreeSet to use
    // PartialValue::Refer instead of having to implement
    // PartialValue::ApplicationPassword. For example
    // btreeset.remove takes a full ApplicationPassword
    // struct.
    map: BTreeMap<Uuid, Vec<ApplicationPassword>>,
}

impl ValueSetApplicationPassword {
    pub fn new(ap: ApplicationPassword) -> Box<Self> {
        let mut map: BTreeMap<Uuid, Vec<ApplicationPassword>> = BTreeMap::new();
        map.entry(ap.application).or_default().push(ap);
        Box::new(ValueSetApplicationPassword { map })
    }

    fn from_dbv_iter(
        data: impl Iterator<Item = DbValueApplicationPassword>,
    ) -> Result<ValueSet, OperationError> {
        let mut map: BTreeMap<Uuid, Vec<ApplicationPassword>> = BTreeMap::new();
        for ap in data {
            let ap = match ap {
                DbValueApplicationPassword::V1 {
                    refer,
                    application_refer,
                    label,
                    password,
                } => {
                    let password = Password::try_from(password)
                        .map_err(|()| OperationError::InvalidValueState)?;
                    ApplicationPassword {
                        uuid: refer,
                        application: application_refer,
                        label,
                        password,
                    }
                }
            };
            map.entry(ap.application).or_default().push(ap);
        }
        Ok(Box::new(ValueSetApplicationPassword { map }))
    }

    pub fn from_dbvs2(data: Vec<DbValueApplicationPassword>) -> Result<ValueSet, OperationError> {
        Self::from_dbv_iter(data.into_iter())
    }

    fn to_vec_dbvs(&self) -> Vec<DbValueApplicationPassword> {
        self.map
            .iter()
            .flat_map(|(_, v)| {
                v.iter().map(|ap| DbValueApplicationPassword::V1 {
                    refer: ap.uuid,
                    application_refer: ap.application,
                    label: ap.label.clone(),
                    password: ap.password.to_dbpasswordv1(),
                })
            })
            .collect()
    }
}

impl ValueSetT for ValueSetApplicationPassword {
    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
        match value {
            Value::ApplicationPassword(ap) => {
                let application_entries = self.map.entry(ap.application).or_default();

                if let Some(application_entry) = application_entries
                    .iter_mut()
                    .find(|entry_app_password| *entry_app_password == &ap)
                {
                    // Overwrite on duplicated labels for the same application.
                    application_entry.password = ap.password;
                } else {
                    // Or just add it.
                    application_entries.push(ap);
                }
                Ok(true)
            }
            _ => Err(OperationError::InvalidValueState),
        }
    }

    fn clear(&mut self) {
        self.map.clear();
    }

    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
        match pv {
            PartialValue::Refer(u) => {
                // Deletes all passwords for the referred application
                self.map.remove(u).is_some()
            }
            PartialValue::Uuid(u) => {
                // Delete specific application password
                // TODO Migrate to extract_if when available
                let mut removed = false;
                self.map.retain(|_, v| {
                    let prev = v.len();
                    // Check the innel vec of passwords related to this application.
                    v.retain(|y| y.uuid != *u);
                    let post = v.len();
                    removed |= post < prev;
                    // Is the apppwd set for this application id now empty?
                    !v.is_empty()
                });
                removed
            }
            _ => false,
        }
    }

    fn contains(&self, pv: &PartialValue) -> bool {
        match pv {
            PartialValue::Uuid(u) => self.map.values().any(|v| v.iter().any(|ap| ap.uuid == *u)),
            PartialValue::Refer(u) => self
                .map
                .values()
                .any(|v| v.iter().any(|ap| ap.application == *u)),
            _ => false,
        }
    }

    fn substring(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn startswith(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn endswith(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn lessthan(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn len(&self) -> usize {
        let mut count = 0;
        for v in self.map.values() {
            count += v.len();
        }
        count
    }

    fn generate_idx_eq_keys(&self) -> Vec<String> {
        self.map
            .keys()
            .map(|u| u.as_hyphenated().to_string())
            .collect()
    }

    fn syntax(&self) -> SyntaxType {
        SyntaxType::ApplicationPassword
    }

    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
        self.map.iter().all(|(_, v)| {
            v.iter().all(|ap| {
                Value::validate_str_escapes(ap.label.as_str())
                    && Value::validate_singleline(ap.label.as_str())
            })
        })
    }

    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
        Box::new(self.map.iter().flat_map(|(_, v)| {
            v.iter()
                .map(|ap| format!("App: {} Label: {}", ap.application, ap.label))
        }))
    }

    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
            self.map
                .values()
                .flatten()
                .map(|app_pwd| ScimApplicationPassword {
                    uuid: app_pwd.uuid,
                    application_uuid: app_pwd.application,
                    label: app_pwd.label.clone(),
                })
                .collect::<Vec<_>>(),
        )))
    }

    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
        let data = self.to_vec_dbvs();
        DbValueSetV2::ApplicationPassword(data)
    }

    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
        Box::new(
            self.map
                .iter()
                .flat_map(|(_, v)| v.iter().map(|ap| ap.uuid))
                .map(PartialValue::Refer),
        )
    }

    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
        Box::new(
            self.map
                .iter()
                .flat_map(|(_, v)| v.iter().map(|ap| Value::ApplicationPassword(ap.clone()))),
        )
    }

    fn equal(&self, other: &ValueSet) -> bool {
        if let Some(other) = other.as_application_password_map() {
            &self.map == other
        } else {
            debug_assert!(false);
            false
        }
    }

    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
        if let Some(b) = other.as_application_password_map() {
            mergemaps!(self.map, b)
        } else {
            debug_assert!(false);
            Err(OperationError::InvalidValueState)
        }
    }

    fn as_application_password_map(&self) -> Option<&BTreeMap<Uuid, Vec<ApplicationPassword>>> {
        Some(&self.map)
    }

    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
        // This is what ties us as a type that can be refint checked.
        Some(Box::new(self.map.keys().copied()))
    }
}

#[cfg(test)]
mod tests {
    use crate::credential::{apppwd::ApplicationPassword, Password};
    use crate::prelude::*;
    use crate::valueset::ValueSetApplicationPassword;
    use kanidm_lib_crypto::CryptoPolicy;

    // Test the remove operation, removing all application passwords for an
    // application should also remove the KV pair.
    #[test]
    fn test_valueset_application_password_remove() {
        let app1_uuid = Uuid::new_v4();
        let app2_uuid = Uuid::new_v4();
        let ap1_uuid = Uuid::new_v4();
        let ap2_uuid = Uuid::new_v4();
        let ap3_uuid = Uuid::new_v4();

        let ap1: ApplicationPassword = ApplicationPassword {
            uuid: ap1_uuid,
            application: app1_uuid,
            label: "apppwd1".to_string(),
            password: Password::new_pbkdf2(&CryptoPolicy::minimum(), "apppwd1")
                .expect("Failed to create password"),
        };

        let ap2: ApplicationPassword = ApplicationPassword {
            uuid: ap2_uuid,
            application: app1_uuid,
            label: "apppwd2".to_string(),
            password: Password::new_pbkdf2(&CryptoPolicy::minimum(), "apppwd2")
                .expect("Failed to create password"),
        };

        let ap3: ApplicationPassword = ApplicationPassword {
            uuid: ap3_uuid,
            application: app2_uuid,
            label: "apppwd3".to_string(),
            password: Password::new_pbkdf2(&CryptoPolicy::minimum(), "apppwd3")
                .expect("Failed to create password"),
        };

        let mut vs: ValueSet = ValueSetApplicationPassword::new(ap1);
        assert_eq!(vs.len(), 1);

        let res = vs
            .insert_checked(Value::ApplicationPassword(ap2))
            .expect("Failed to insert");
        assert!(res);
        assert_eq!(vs.len(), 2);

        let res = vs
            .insert_checked(Value::ApplicationPassword(ap3))
            .expect("Failed to insert");
        assert!(res);
        assert_eq!(vs.len(), 3);

        let res = vs.remove(&PartialValue::Uuid(Uuid::new_v4()), &Cid::new_zero());
        assert!(!res);
        assert_eq!(vs.len(), 3);

        let res = vs.remove(&PartialValue::Uuid(ap1_uuid), &Cid::new_zero());
        assert!(res);
        assert_eq!(vs.len(), 2);

        let res = vs.remove(&PartialValue::Uuid(ap3_uuid), &Cid::new_zero());
        assert!(res);
        assert_eq!(vs.len(), 1);

        let res = vs.remove(&PartialValue::Uuid(ap2_uuid), &Cid::new_zero());
        assert!(res);
        assert_eq!(vs.len(), 0);

        let res = vs.as_application_password_map().unwrap();
        assert_eq!(res.keys().len(), 0);
    }

    #[test]
    fn test_scim_application_password() {
        let app1_uuid = uuid::uuid!("7c3cd2b4-dc0d-43f5-999c-4912c2412405");
        let app2_uuid = uuid::uuid!("82eaeca8-4250-4b63-a94b-75a3764a9327");
        let ap1_uuid = uuid::uuid!("f36434ba-087a-4774-90ea-ebcda7f8c549");
        let ap2_uuid = uuid::uuid!("b78506c7-eb7a-45d8-a994-34e868ee1a9e");
        let ap3_uuid = uuid::uuid!("740a9d06-1188-4c48-9c5c-dbf863712c66");

        let ap1: ApplicationPassword = ApplicationPassword {
            uuid: ap1_uuid,
            application: app1_uuid,
            label: "apppwd1".to_string(),
            password: Password::new_pbkdf2(&CryptoPolicy::minimum(), "apppwd1")
                .expect("Failed to create password"),
        };

        let ap2: ApplicationPassword = ApplicationPassword {
            uuid: ap2_uuid,
            application: app1_uuid,
            label: "apppwd2".to_string(),
            password: Password::new_pbkdf2(&CryptoPolicy::minimum(), "apppwd2")
                .expect("Failed to create password"),
        };

        let ap3: ApplicationPassword = ApplicationPassword {
            uuid: ap3_uuid,
            application: app2_uuid,
            label: "apppwd3".to_string(),
            password: Password::new_pbkdf2(&CryptoPolicy::minimum(), "apppwd3")
                .expect("Failed to create password"),
        };

        let mut vs: ValueSet = ValueSetApplicationPassword::new(ap1);
        vs.insert_checked(Value::ApplicationPassword(ap2))
            .expect("Failed to insert");
        vs.insert_checked(Value::ApplicationPassword(ap3))
            .expect("Failed to insert");

        let data = r#"
[
  {
    "applicationUuid": "7c3cd2b4-dc0d-43f5-999c-4912c2412405",
    "label": "apppwd1",
    "uuid": "f36434ba-087a-4774-90ea-ebcda7f8c549"
  },
  {
    "applicationUuid": "7c3cd2b4-dc0d-43f5-999c-4912c2412405",
    "label": "apppwd2",
    "uuid": "b78506c7-eb7a-45d8-a994-34e868ee1a9e"
  },
  {
    "applicationUuid": "82eaeca8-4250-4b63-a94b-75a3764a9327",
    "label": "apppwd3",
    "uuid": "740a9d06-1188-4c48-9c5c-dbf863712c66"
  }
]
"#;
        crate::valueset::scim_json_reflexive(vs, data);
    }
}