ssh2-config 0.7.1

an ssh configuration parser for ssh2-rs
Documentation
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::fmt;
use std::str::FromStr;

use crate::SshParserError;

const ID_APPEND: char = '+';
const ID_HEAD: char = '^';
const ID_EXCLUDE: char = '-';

/// List of algorithms to be used.
/// The algorithms can be appended to the default set, placed at the head of the list,
/// excluded from the default set, or set as the default set.
///
/// # Configuring SSH Algorithms
///
/// In order to configure ssh you should use the `to_string()` method to get the string representation
/// with the correct format for ssh2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Algorithms {
    /// Algorithms to be used.
    algos: Vec<String>,
    /// whether the default algorithms have been overridden
    overridden: bool,
    /// applied rule
    rule: Option<AlgorithmsRule>,
}

impl Algorithms {
    /// Create a new instance of [`Algorithms`] with the given default algorithms.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use ssh2_config::Algorithms;
    ///
    /// let algos = Algorithms::new(&["aes128-ctr", "aes192-ctr"]);
    /// ```
    pub fn new<I, S>(default: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        Self {
            algos: default
                .into_iter()
                .map(|s| s.as_ref().to_string())
                .collect(),
            overridden: false,
            rule: None,
        }
    }
}

/// List of algorithms to be used.
/// The algorithms can be appended to the default set, placed at the head of the list,
/// excluded from the default set, or set as the default set.
///
/// # Configuring SSH Algorithms
///
/// In order to configure ssh you should use the `to_string()` method to get the string representation
/// with the correct format for ssh2.
///
/// # Algorithms vector
///
/// Otherwise you can access the inner [`Vec`] of algorithms with the [`Algorithms::algos`] method.
///
/// Beware though, that you must **TAKE CARE of the current variant**.
///
/// For instance in case the variant is [`Algorithms::Exclude`] the algos contained in the vec are the ones **to be excluded**.
///
/// While in case of [`Algorithms::Append`] the algos contained in the vec are the ones to be appended to the default ones.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AlgorithmsRule {
    /// Append the given algorithms to the default set.
    Append(Vec<String>),
    /// Place the given algorithms at the head of the list.
    Head(Vec<String>),
    /// Exclude the given algorithms from the default set.
    Exclude(Vec<String>),
    /// Set the given algorithms as the default set.
    Set(Vec<String>),
}

/// Rule applied; used to format algorithms
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AlgorithmsOp {
    Append,
    Head,
    Exclude,
    Set,
}

impl Algorithms {
    /// Returns whether the default algorithms are being used.
    pub fn is_default(&self) -> bool {
        !self.overridden
    }

    /// Returns algorithms to be used.
    pub fn algorithms(&self) -> &[String] {
        &self.algos
    }

    /// Apply an `AlgorithmsRule` to the [`Algorithms`] instance.
    ///
    /// If defaults haven't been overridden, apply changes from incoming rule;
    /// otherwise keep as-is.
    pub fn apply(&mut self, rule: AlgorithmsRule) {
        if self.overridden {
            // don't apply changes if defaults have been overridden
            return;
        }

        let mut current_algos = self.algos.clone();

        match rule.clone() {
            AlgorithmsRule::Append(algos) => {
                // append but exclude duplicates
                for algo in algos {
                    if !current_algos.iter().any(|s| s == &algo) {
                        current_algos.push(algo);
                    }
                }
            }
            AlgorithmsRule::Head(algos) => {
                current_algos = algos;
                current_algos.extend(self.algorithms().iter().map(|s| s.to_string()));
            }
            AlgorithmsRule::Exclude(exclude) => {
                current_algos = current_algos
                    .iter()
                    .filter(|algo| !exclude.contains(algo))
                    .map(|s| s.to_string())
                    .collect();
            }
            AlgorithmsRule::Set(algos) => {
                // override default with new set
                current_algos = algos;
            }
        }

        // apply changes
        self.rule = Some(rule);
        self.algos = current_algos;
        self.overridden = true;
    }
}

impl AlgorithmsRule {
    fn op(&self) -> AlgorithmsOp {
        match self {
            Self::Append(_) => AlgorithmsOp::Append,
            Self::Head(_) => AlgorithmsOp::Head,
            Self::Exclude(_) => AlgorithmsOp::Exclude,
            Self::Set(_) => AlgorithmsOp::Set,
        }
    }
}

impl FromStr for AlgorithmsRule {
    type Err = SshParserError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(SshParserError::ExpectedAlgorithms);
        }

        // get first char
        let (op, start) = match s.chars().next().expect("can't be empty") {
            ID_APPEND => (AlgorithmsOp::Append, 1),
            ID_HEAD => (AlgorithmsOp::Head, 1),
            ID_EXCLUDE => (AlgorithmsOp::Exclude, 1),
            _ => (AlgorithmsOp::Set, 0),
        };

        let algos = s[start..]
            .split(',')
            .map(|s| s.trim().to_string())
            .collect::<Vec<String>>();

        match op {
            AlgorithmsOp::Append => Ok(Self::Append(algos)),
            AlgorithmsOp::Head => Ok(Self::Head(algos)),
            AlgorithmsOp::Exclude => Ok(Self::Exclude(algos)),
            AlgorithmsOp::Set => Ok(Self::Set(algos)),
        }
    }
}

impl fmt::Display for AlgorithmsRule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let op = self.op();
        write!(f, "{op}")
    }
}

impl fmt::Display for AlgorithmsOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self {
            Self::Append => write!(f, "{ID_APPEND}"),
            Self::Head => write!(f, "{ID_HEAD}"),
            Self::Exclude => write!(f, "{ID_EXCLUDE}"),
            Self::Set => write!(f, ""),
        }
    }
}

impl fmt::Display for Algorithms {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(rule) = self.rule.as_ref() {
            write!(f, "{rule}",)
        } else {
            write!(f, "{}", self.algos.join(","))
        }
    }
}

#[cfg(test)]
mod tests {

    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn test_should_parse_algos_set() {
        let algo =
            AlgorithmsRule::from_str("aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse");
        assert_eq!(
            algo,
            AlgorithmsRule::Set(vec![
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string(),
                "aes256-ctr".to_string()
            ])
        );
    }

    #[test]
    fn test_should_parse_algos_append() {
        let algo =
            AlgorithmsRule::from_str("+aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse");
        assert_eq!(
            algo,
            AlgorithmsRule::Append(vec![
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string(),
                "aes256-ctr".to_string()
            ])
        );
    }

    #[test]
    fn test_should_parse_algos_head() {
        let algo =
            AlgorithmsRule::from_str("^aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse");
        assert_eq!(
            algo,
            AlgorithmsRule::Head(vec![
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string(),
                "aes256-ctr".to_string()
            ])
        );
    }

    #[test]
    fn test_should_parse_algos_exclude() {
        let algo =
            AlgorithmsRule::from_str("-aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse");
        assert_eq!(
            algo,
            AlgorithmsRule::Exclude(vec![
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string(),
                "aes256-ctr".to_string()
            ])
        );
    }

    #[test]
    fn test_should_apply_append() {
        let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]);
        let algo2 = AlgorithmsRule::from_str("+aes256-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(
            algo1.algorithms(),
            vec![
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string(),
                "aes256-ctr".to_string()
            ]
        );
    }

    #[test]
    fn test_should_merge_append_if_undefined() {
        let algos: Vec<String> = vec![];
        let mut algo1 = Algorithms::new(algos);
        let algo2 = AlgorithmsRule::from_str("+aes256-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string()]);
    }

    #[test]
    fn test_should_merge_head() {
        let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]);
        let algo2 = AlgorithmsRule::from_str("^aes256-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(
            algo1.algorithms(),
            vec![
                "aes256-ctr".to_string(),
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string()
            ]
        );
    }

    #[test]
    fn test_should_apply_head() {
        let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]);
        let algo2 = AlgorithmsRule::from_str("^aes256-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(
            algo1.algorithms(),
            vec![
                "aes256-ctr".to_string(),
                "aes128-ctr".to_string(),
                "aes192-ctr".to_string()
            ]
        );
    }

    #[test]
    fn test_should_merge_exclude() {
        let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr", "aes256-ctr"]);
        let algo2 = AlgorithmsRule::from_str("-aes192-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(
            algo1.algorithms(),
            vec!["aes128-ctr".to_string(), "aes256-ctr".to_string()]
        );
    }

    #[test]
    fn test_should_merge_set() {
        let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]);
        let algo2 = AlgorithmsRule::from_str("aes256-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string()]);
    }

    #[test]
    fn test_should_not_apply_twice() {
        let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]);
        let algo2 = AlgorithmsRule::from_str("aes256-ctr").expect("failed to parse");
        algo1.apply(algo2);
        assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string(),]);

        let algo3 = AlgorithmsRule::from_str("aes128-ctr").expect("failed to parse");
        algo1.apply(algo3);
        assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string()]);
        assert_eq!(algo1.overridden, true);
    }

    #[test]
    fn test_algorithms_display_with_rule() {
        let mut algos = Algorithms::new(&["aes128-ctr"]);

        // Apply append rule
        let rule = AlgorithmsRule::from_str("+aes256-ctr").expect("failed to parse");
        algos.apply(rule);

        // Display should show the rule prefix
        let display = algos.to_string();
        assert_eq!(display, "+");
    }

    #[test]
    fn test_algorithms_display_without_rule() {
        let algos = Algorithms::new(&["aes128-ctr", "aes256-ctr"]);
        let display = algos.to_string();
        assert_eq!(display, "aes128-ctr,aes256-ctr");
    }

    #[test]
    fn test_algorithms_rule_display() {
        let append = AlgorithmsRule::from_str("+algo").expect("failed to parse");
        assert_eq!(append.to_string(), "+");

        let head = AlgorithmsRule::from_str("^algo").expect("failed to parse");
        assert_eq!(head.to_string(), "^");

        let exclude = AlgorithmsRule::from_str("-algo").expect("failed to parse");
        assert_eq!(exclude.to_string(), "-");

        let set = AlgorithmsRule::from_str("algo").expect("failed to parse");
        assert_eq!(set.to_string(), "");
    }

    #[test]
    fn test_algorithms_is_default() {
        let algos = Algorithms::new(&["aes128-ctr"]);
        assert!(algos.is_default());

        let mut algos2 = Algorithms::new(&["aes128-ctr"]);
        algos2.apply(AlgorithmsRule::from_str("aes256-ctr").expect("failed to parse"));
        assert!(!algos2.is_default());
    }

    #[test]
    fn test_parse_empty_algos_returns_error() {
        let result = AlgorithmsRule::from_str("");
        assert!(result.is_err());
    }

    #[test]
    fn test_append_with_duplicate_algorithms() {
        let mut algos = Algorithms::new(&["aes128-ctr", "aes256-ctr"]);
        let rule = AlgorithmsRule::from_str("+aes128-ctr,aes512-ctr").expect("failed to parse");
        algos.apply(rule);
        // aes128-ctr should not be duplicated
        assert_eq!(
            algos.algorithms(),
            vec![
                "aes128-ctr".to_string(),
                "aes256-ctr".to_string(),
                "aes512-ctr".to_string()
            ]
        );
    }

    #[test]
    fn test_exclude_all_algorithms() {
        let mut algos = Algorithms::new(&["aes128-ctr", "aes256-ctr"]);
        let rule = AlgorithmsRule::from_str("-aes128-ctr,aes256-ctr").expect("failed to parse");
        algos.apply(rule);
        assert!(algos.algorithms().is_empty());
    }

    #[test]
    fn test_head_with_empty_defaults() {
        let empty: Vec<String> = vec![];
        let mut algos = Algorithms::new(empty);
        let rule = AlgorithmsRule::from_str("^aes256-ctr").expect("failed to parse");
        algos.apply(rule);
        assert_eq!(algos.algorithms(), vec!["aes256-ctr".to_string()]);
    }

    #[test]
    fn test_algorithms_rule_op() {
        let append = AlgorithmsRule::Append(vec!["algo".to_string()]);
        assert_eq!(append.op(), AlgorithmsOp::Append);

        let head = AlgorithmsRule::Head(vec!["algo".to_string()]);
        assert_eq!(head.op(), AlgorithmsOp::Head);

        let exclude = AlgorithmsRule::Exclude(vec!["algo".to_string()]);
        assert_eq!(exclude.op(), AlgorithmsOp::Exclude);

        let set = AlgorithmsRule::Set(vec!["algo".to_string()]);
        assert_eq!(set.op(), AlgorithmsOp::Set);
    }
}