Skip to main content

kanidmd_lib/valueset/
ssh.rs

1use crate::{
2    be::dbvalue::DbValueTaggedStringV1,
3    prelude::*,
4    schema::SchemaAttribute,
5    utils::trigraph_iter,
6    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
7};
8use kanidm_proto::scim_v1::{JsonValue, ScimSshPublicKey};
9use sshkey_attest::proto::PublicKey as SshPublicKey;
10use std::collections::{btree_map::Entry as BTreeEntry, BTreeMap};
11
12#[derive(Debug, Clone)]
13pub struct ValueSetSshKey {
14    map: BTreeMap<String, SshPublicKey>,
15}
16
17impl ValueSetSshKey {
18    pub fn new(t: String, k: SshPublicKey) -> Box<Self> {
19        let mut map = BTreeMap::new();
20        map.insert(t, k);
21        Box::new(ValueSetSshKey { map })
22    }
23
24    pub fn push(&mut self, t: String, k: SshPublicKey) -> bool {
25        self.map.insert(t, k).is_none()
26    }
27
28    pub fn from_dbvs2(data: Vec<DbValueTaggedStringV1>) -> Result<ValueSet, OperationError> {
29        let map = data
30            .into_iter()
31            .filter_map(|DbValueTaggedStringV1 { tag, data }| {
32                SshPublicKey::from_string(&data)
33                    .map_err(|err| {
34                        warn!(%tag, ?err, "discarding corrupted ssh public key");
35                    })
36                    .map(|pk| {
37                        if tag.is_empty() {
38                            // No tag was known - use the hash of the key to guarantee it's unique.
39                            // New keys can't be created with empty strs
40                            (pk.fingerprint().hash, pk)
41                        } else {
42                            (tag, pk)
43                        }
44                    })
45                    .ok()
46            })
47            .collect();
48        Ok(Box::new(ValueSetSshKey { map }))
49    }
50
51    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
52    // types, and tuples are always foreign.
53    #[allow(clippy::should_implement_trait)]
54    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
55    where
56        T: IntoIterator<Item = (String, SshPublicKey)>,
57    {
58        let map = iter.into_iter().collect();
59        Some(Box::new(ValueSetSshKey { map }))
60    }
61}
62
63impl ValueSetScimPut for ValueSetSshKey {
64    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
65        let value: Vec<ScimSshPublicKey> = serde_json::from_value(value).map_err(|err| {
66            error!(?err, "SCIM Ssh Public Key syntax invalid");
67            OperationError::SC0024SshPublicKeySyntaxInvalid
68        })?;
69
70        let map = value
71            .into_iter()
72            .map(|ScimSshPublicKey { label, value }| (label, value))
73            .collect();
74
75        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetSshKey {
76            map,
77        })))
78    }
79}
80
81impl ValueSetT for ValueSetSshKey {
82    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
83        match value {
84            Value::SshKey(t, k) => {
85                if let BTreeEntry::Vacant(e) = self.map.entry(t) {
86                    e.insert(k);
87                    Ok(true)
88                } else {
89                    Ok(false)
90                }
91            }
92            _ => Err(OperationError::InvalidValueState),
93        }
94    }
95
96    fn clear(&mut self) {
97        self.map.clear();
98    }
99
100    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
101        if let PartialValue::SshKey(t) = pv {
102            self.map.remove(t.as_str());
103        };
104        self.map.is_empty()
105    }
106
107    fn contains(&self, pv: &PartialValue) -> bool {
108        match pv {
109            PartialValue::SshKey(t) => self.map.contains_key(t.as_str()),
110            _ => false,
111        }
112    }
113
114    fn substring(&self, _pv: &PartialValue) -> bool {
115        false
116    }
117
118    fn startswith(&self, _pv: &PartialValue) -> bool {
119        false
120    }
121
122    fn endswith(&self, _pv: &PartialValue) -> bool {
123        false
124    }
125
126    fn lessthan(&self, _pv: &PartialValue) -> bool {
127        false
128    }
129
130    fn len(&self) -> usize {
131        self.map.len()
132    }
133
134    fn generate_idx_eq_keys(&self) -> Vec<String> {
135        self.map.keys().cloned().collect()
136    }
137
138    fn generate_idx_sub_keys(&self) -> Vec<String> {
139        let lower: Vec<_> = self.map.keys().map(|s| s.to_lowercase()).collect();
140        let mut trigraphs: Vec<_> = lower.iter().flat_map(|v| trigraph_iter(v)).collect();
141
142        trigraphs.sort_unstable();
143        trigraphs.dedup();
144
145        trigraphs.into_iter().map(String::from).collect()
146    }
147
148    fn syntax(&self) -> SyntaxType {
149        SyntaxType::SshKey
150    }
151
152    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
153        self.map.iter().all(|(s, _key)| {
154            !s.is_empty() &&
155            Value::validate_str_escapes(s)
156                // && Value::validate_iname(s)
157                && Value::validate_singleline(s)
158        })
159    }
160
161    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
162        Box::new(self.map.iter().map(|(tag, pk)| format!("{tag}: {pk}")))
163    }
164
165    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
166        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
167            self.map
168                .iter()
169                .map(|(label, value)| ScimSshPublicKey {
170                    label: label.clone(),
171                    value: value.clone(),
172                })
173                .collect::<Vec<_>>(),
174        )))
175    }
176
177    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
178        DbValueSetV2::SshKey(
179            self.map
180                .iter()
181                .map(|(tag, key)| DbValueTaggedStringV1 {
182                    tag: tag.clone(),
183                    data: key.to_string(),
184                })
185                .collect(),
186        )
187    }
188
189    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
190        Box::new(self.map.keys().cloned().map(PartialValue::SshKey))
191    }
192
193    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
194        Box::new(
195            self.map
196                .iter()
197                .map(|(t, k)| Value::SshKey(t.clone(), k.clone())),
198        )
199    }
200
201    fn equal(&self, other: &ValueSet) -> bool {
202        if let Some(other) = other.as_sshkey_map() {
203            &self.map == other
204        } else {
205            debug_assert!(false);
206            false
207        }
208    }
209
210    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
211        if let Some(b) = other.as_sshkey_map() {
212            mergemaps!(self.map, b)
213        } else {
214            debug_assert!(false);
215            Err(OperationError::InvalidValueState)
216        }
217    }
218
219    fn as_sshkey_map(&self) -> Option<&BTreeMap<String, SshPublicKey>> {
220        Some(&self.map)
221    }
222
223    fn get_ssh_tag(&self, tag: &str) -> Option<&SshPublicKey> {
224        self.map.get(tag)
225    }
226
227    fn as_sshpubkey_string_iter(&self) -> Option<Box<dyn Iterator<Item = String> + '_>> {
228        Some(Box::new(self.map.values().map(|pk| pk.to_string())))
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::{SshPublicKey, ValueSetSshKey};
235    use crate::prelude::ValueSet;
236
237    #[test]
238    fn test_scim_ssh_public_key() {
239        let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
240        "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
241        "zPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag== william@a",
242        "methyst");
243
244        let vs: ValueSet = ValueSetSshKey::new(
245            "label".to_string(),
246            SshPublicKey::from_string(ecdsa).unwrap(),
247        );
248
249        let data = r#"
250[
251  {
252    "label": "label",
253    "value": "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3BtOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81lzPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag== william@amethyst"
254  }
255]
256        "#;
257        crate::valueset::scim_json_reflexive(&vs, data);
258
259        // Test that we can parse json values into a valueset.
260        crate::valueset::scim_json_put_reflexive::<ValueSetSshKey>(&vs, &[])
261    }
262
263    #[test]
264    /// this is a test case for bad characters in SSH keys
265    fn test_invalid_character() {
266        let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEÀAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
267        //                                                                      ^ note the À here
268        "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
269        "zPrVSdrYEDldxH9+a86dBZhdm0è15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag== william@a",
270        "methyst");
271        println!("bytes of À {:?}", "À".as_bytes());
272        let found_index = ecdsa.find("À").expect("Failed to find è in string");
273        assert_eq!(found_index, 51, "Expected index 51");
274        let bad_ssh_error = SshPublicKey::from_string(ecdsa);
275
276        assert!(
277            bad_ssh_error.is_err(),
278            "Expected error, but got: {bad_ssh_error:?}"
279        );
280        if let Err(err) = bad_ssh_error {
281            assert_eq!(
282                err.to_string(),
283                format!("Invalid symbol 195, offset {}.", found_index - 20)
284            ); // the offset is 31 because the string has a 20 character leading key type plus the space
285        }
286    }
287
288    #[test]
289    /// this is a test case for bad characters in SSH keys
290    fn test_assert_comments() {
291        // Comment is okay.
292        let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
293        "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
294        "zPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag== william@a",
295        "methyst");
296
297        let _ = SshPublicKey::from_string(ecdsa).unwrap();
298
299        // No comment is okay.
300        let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
301        "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
302        "zPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag==");
303
304        let _ = SshPublicKey::from_string(ecdsa).unwrap();
305
306        // No comment is okay (spaces to end of line)
307        let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
308        "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
309        "zPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag==     ");
310
311        let _ = SshPublicKey::from_string(ecdsa).unwrap();
312
313        // Comment may have spaces
314        let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
315        "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
316        "zPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag==  I'm a giraffe! ");
317
318        let _ = SshPublicKey::from_string(ecdsa).unwrap();
319    }
320}