tor-keymgr 0.42.0

Key management for the Arti Tor implementation
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! [`ArtiPath`] and its associated helpers.

use std::str::FromStr;

use derive_deftly::{Deftly, define_derive_deftly};
use derive_more::{Deref, Display, Into};
use serde::{Deserialize, Serialize};
use tor_persist::slug::{self, BadSlug};

use crate::{ArtiPathRange, ArtiPathSyntaxError, KeySpecifierComponent};

// TODO: this is only used for ArtiPaths (we should consider turning this
// intro a regular impl ArtiPath {} and removing the macro).
define_derive_deftly! {
    /// Implement `new()`, `TryFrom<String>` in terms of `validate_str`, and `as_ref<str>`
    //
    // TODO maybe this is generally useful?  Or maybe we should find a crate?
    ValidatedString for struct, expect items:

    impl $ttype {
        #[doc = concat!("Create a new [`", stringify!($tname), "`].")]
        ///
        /// This function returns an error if `inner` is not in the right syntax.
        pub fn new(inner: String) -> Result<Self, ArtiPathSyntaxError> {
            Self::validate_str(&inner)?;
            Ok(Self(inner))
        }
    }

    impl TryFrom<String> for $ttype {
        type Error = ArtiPathSyntaxError;

        fn try_from(s: String) -> Result<Self, ArtiPathSyntaxError> {
            Self::new(s)
        }
    }

    impl FromStr for $ttype {
        type Err = ArtiPathSyntaxError;

        fn from_str(s: &str) -> Result<Self, ArtiPathSyntaxError> {
            Self::validate_str(s)?;
            Ok(Self(s.to_owned()))
        }
    }

    impl AsRef<str> for $ttype {
        fn as_ref(&self) -> &str {
            &self.0.as_str()
        }
    }
}

/// A unique identifier for a particular instance of a key.
///
/// In an [`ArtiNativeKeystore`](crate::ArtiNativeKeystore), this also represents the path of the
/// key relative to the root of the keystore, minus the file extension.
///
/// An `ArtiPath` is a nonempty sequence of [`Slug`](tor_persist::slug::Slug)s, separated by `/`.  Path
/// components may contain lowercase ASCII alphanumerics, and  `-` or `_`.
/// See [slug] for the full syntactic requirements.
/// Consequently, leading or trailing or duplicated / are forbidden.
///
/// The last component of the path may optionally contain the encoded (string) representation
/// of one or more *denotator groups*.
/// A denotator group consists
/// of one or more
/// [`KeySpecifierComponent`]
/// s representing the denotators of the key.
/// [`DENOTATOR_SEP`] denotes the beginning of the denotator groups.
///
/// Within a denotator group, denotators are separated
/// by [`DENOTATOR_SEP`] characters.
///
/// Denotator groups are separated from each other
/// by [`DENOTATOR_GROUP_SEP`] characters.
///
/// Empty denotator groups are allowed,
/// but trailing empty denotator groups are not represented in `ArtiPath`s.
/// Consequently, two abstract paths which differ only
/// in trailing empty denotator groups cannot be distinguished;
/// or to put it another way, the number of denotator groups
/// is not recoverable from the path.
///
/// Denotators are encoded using their
/// [`KeySpecifierComponent::to_slug`]
/// implementation.
/// The denotators **must** come after all the other fields.
/// Denotator strings are validated in the same way as [`Slug`](tor-persist::slug::Slug)s.
///
/// For example, the last component of the path `"foo/bar/bax+denotator_example+1"`
/// is the denotator group `"denotator_example+1"`.
/// Its denotators are `"denotator_example"` and `"1"` (encoded as strings).
/// As another example, the path `"foo/bar/bax+denotator_example+1@foo+bar@baz"`
/// has three denotator groups, separated by `@`,
/// `"denotator_example+1"`, `foo+bar`, and `baz`.
///
/// NOTE: There is a 1:1 mapping between a value that implements `KeySpecifier` and its
/// corresponding `ArtiPath`. A `KeySpecifier` can be converted to an `ArtiPath`, but the reverse
/// conversion is not supported.
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Deref, Into, Display)] //
#[derive(Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
#[derive(Deftly)]
#[derive_deftly(ValidatedString)]
pub struct ArtiPath(String);

/// A separator for `ArtiPath`s.
pub(crate) const PATH_SEP: char = '/';

/// A separator for that marks the beginning of the keys denotators
/// within an [`ArtiPath`].
///
/// This separator can only appear within the last component of an [`ArtiPath`],
/// and the substring that follows it is assumed to be the string representation
/// of the denotator groups of the path.
pub const DENOTATOR_SEP: char = '+';

/// A separator for separating individual denotator groups from each other.
pub const DENOTATOR_GROUP_SEP: char = '@';

impl ArtiPath {
    /// Validate the underlying representation of an `ArtiPath`
    fn validate_str(inner: &str) -> Result<(), ArtiPathSyntaxError> {
        // Validate the denotators, if there are any.
        let path = if let Some((main_part, denotator_groups)) = inner.split_once(DENOTATOR_SEP) {
            for denotators in denotator_groups.split(DENOTATOR_GROUP_SEP) {
                let () = validate_denotator_group(denotators)?;
            }

            main_part
        } else {
            inner
        };

        if let Some(e) = path
            .split(PATH_SEP)
            .map(|s| {
                if s.is_empty() {
                    Err(BadSlug::EmptySlugNotAllowed.into())
                } else {
                    Ok(slug::check_syntax(s)?)
                }
            })
            .find(|e| e.is_err())
        {
            return e;
        }

        Ok(())
    }

    /// Return the substring corresponding to the specified `range`.
    ///
    /// Returns `None` if `range` is not within the bounds of this `ArtiPath`.
    ///
    /// ### Example
    /// ```
    /// # use tor_keymgr::{ArtiPath, ArtiPathRange, ArtiPathSyntaxError};
    /// # fn demo() -> Result<(), ArtiPathSyntaxError> {
    /// let path = ArtiPath::new("foo_bar_bax_1".into())?;
    ///
    /// let range = ArtiPathRange::from(2..5);
    /// assert_eq!(path.substring(&range), Some("o_b"));
    ///
    /// let range = ArtiPathRange::from(22..50);
    /// assert_eq!(path.substring(&range), None);
    /// # Ok(())
    /// # }
    /// #
    /// # demo().unwrap();
    /// ```
    pub fn substring(&self, range: &ArtiPathRange) -> Option<&str> {
        self.0.get(range.0.clone())
    }

    /// Create an `ArtiPath` from an `ArtiPath` and a list of denotators.
    ///
    /// If `cert_denotators` is empty, returns the specified `path` as-is.
    /// Otherwise, returns an `ArtiPath` that consists of the specified `path`
    /// followed by a [`DENOTATOR_GROUP_SEP`] character and the specified denotators
    /// (the denotators are encoded as described in the [`ArtiPath`] docs).
    ///
    /// Returns an error if any of the specified denotators are not valid `Slug`s.
    //
    /// ### Example
    /// ```nocompile
    /// # // `nocompile` because this function is not pub
    /// # use tor_keymgr::{
    /// #    ArtiPath, ArtiPathRange, ArtiPathSyntaxError, KeySpecifierComponent,
    /// #    KeySpecifierComponentViaDisplayFromStr,
    /// # };
    /// # use derive_more::{Display, FromStr};
    /// # #[derive(Display, FromStr)]
    /// # struct Denotator(String);
    /// # impl KeySpecifierComponentViaDisplayFromStr for Denotator {}
    /// # fn demo() -> Result<(), ArtiPathSyntaxError> {
    /// let path = ArtiPath::new("my_key_path".into())?;
    /// let denotators = [
    ///    &Denotator("foo".to_string()) as &dyn KeySpecifierComponent,
    ///    &Denotator("bar".to_string()) as &dyn KeySpecifierComponent,
    /// ];
    ///
    /// let expected_path = ArtiPath::new("my_key_path+foo+bar".into())?;
    ///
    /// assert_eq!(
    ///    ArtiPath::from_path_and_denotators(path.clone(), &denotators[..])?,
    ///    expected_path
    /// );
    ///
    /// assert_eq!(
    ///    ArtiPath::from_path_and_denotators(path.clone(), &[])?,
    ///    path
    /// );
    /// # Ok(())
    /// # }
    /// #
    /// # demo().unwrap();
    /// ```
    pub(crate) fn from_path_and_denotators(
        path: ArtiPath,
        cert_denotators: &[&dyn KeySpecifierComponent],
    ) -> Result<ArtiPath, ArtiPathSyntaxError> {
        if cert_denotators.is_empty() {
            return Ok(path);
        }

        let cert_denotators = cert_denotators
            .iter()
            .map(|s| s.to_slug().map(|s| s.to_string()))
            .collect::<Result<Vec<_>, _>>()?
            .join(&DENOTATOR_SEP.to_string());

        let path = if cert_denotators.is_empty() {
            format!("{path}")
        } else {
            // If the path already contains some denotators,
            // we need to use the denotator group separator
            // to separate them from the certificate denotators.
            // Otherwise, we simply use the regular DENOTATOR_SEP
            // to indicate the start of the denotator section.
            if path.contains(DENOTATOR_SEP) {
                format!("{path}{DENOTATOR_GROUP_SEP}{cert_denotators}")
            } else {
                // If the key path has no denotators, we need to manually insert
                // an empty denotator group before the `cert_denotators` denotator group.
                // This ensures the origin (key vs cert specifier) of the denotators is unambiguous.
                format!("{path}{DENOTATOR_SEP}{DENOTATOR_GROUP_SEP}{cert_denotators}")
            }
        };

        ArtiPath::new(path)
    }
}

/// Validate a single denotator group.
fn validate_denotator_group(denotators: &str) -> Result<(), ArtiPathSyntaxError> {
    // Empty denotator groups are allowed
    if denotators.is_empty() {
        return Ok(());
    }

    for d in denotators.split(DENOTATOR_SEP) {
        let () = slug::check_syntax(d)?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;

    use derive_more::{Display, FromStr};
    use itertools::chain;

    use crate::KeySpecifierComponentViaDisplayFromStr;

    impl PartialEq for ArtiPathSyntaxError {
        fn eq(&self, other: &Self) -> bool {
            use ArtiPathSyntaxError::*;

            match (self, other) {
                (Slug(err1), Slug(err2)) => err1 == err2,
                _ => false,
            }
        }
    }

    macro_rules! assert_ok {
        ($ty:ident, $inner:expr) => {{
            let path = $ty::new($inner.to_string());
            let path_fromstr: Result<$ty, _> = $ty::try_from($inner.to_string());
            let path_tryfrom: Result<$ty, _> = $inner.to_string().try_into();
            assert!(path.is_ok(), "{} should be valid", $inner);
            assert_eq!(path.as_ref().unwrap().to_string(), *$inner);
            assert_eq!(path, path_fromstr);
            assert_eq!(path, path_tryfrom);
        }};
    }

    fn assert_err(path: &str, error_kind: ArtiPathSyntaxError) {
        let path_anew = ArtiPath::new(path.to_string());
        let path_fromstr = ArtiPath::try_from(path.to_string());
        let path_tryfrom: Result<ArtiPath, _> = path.to_string().try_into();
        assert!(path_anew.is_err(), "{} should be invalid", path);
        let actual_err = path_anew.as_ref().unwrap_err();
        assert_eq!(actual_err, &error_kind);
        assert_eq!(path_anew, path_fromstr);
        assert_eq!(path_anew, path_tryfrom);
    }

    #[derive(Display, FromStr)]
    struct Denotator(String);

    impl KeySpecifierComponentViaDisplayFromStr for Denotator {}

    #[test]
    fn arti_path_from_path_and_denotators() {
        let denotators = [
            &Denotator("foo".to_string()) as &dyn KeySpecifierComponent,
            &Denotator("bar".to_string()) as &dyn KeySpecifierComponent,
            &Denotator("baz".to_string()) as &dyn KeySpecifierComponent,
        ];

        /// Base ArtiPaths and the expected outcome from concatenating
        /// the base with the denotator group above.
        const TEST_PATHS: &[(&str, &str)] = &[
            // A base path with no denotator groups
            ("my_key_path", "my_key_path+@foo+bar+baz"),
            // A base path with a single denotator groups
            ("my_key_path+dino+saur", "my_key_path+dino+saur@foo+bar+baz"),
            // A base path with two denotator groups
            ("my_key_path+dino@saur", "my_key_path+dino@saur@foo+bar+baz"),
            // A base path with two empty denotator groups
            (
                "my_key_path+dino@@@saur",
                "my_key_path+dino@@@saur@foo+bar+baz",
            ),
        ];

        for (base_path, expected_path) in TEST_PATHS {
            let path = ArtiPath::new(base_path.to_string()).unwrap();
            let expected_path = ArtiPath::new(expected_path.to_string()).unwrap();

            assert_eq!(
                ArtiPath::from_path_and_denotators(path.clone(), &denotators[..]).unwrap(),
                expected_path
            );

            assert_eq!(
                ArtiPath::from_path_and_denotators(path.clone(), &[]).unwrap(),
                path
            );
        }
    }

    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn arti_path_validation() {
        const VALID_ARTI_PATH_COMPONENTS: &[&str] = &["my-hs-client-2", "hs_client"];
        const VALID_ARTI_PATHS: &[&str] = &[
            "path/to/client+subvalue+fish",
            "_hs_client",
            "hs_client-",
            "hs_client_",
            "_",
            // A path with an empty denotator group
            "my_key_path+dino@@saur",
            // Paths with a trailing empty denotator group.
            // Our implementation doesn't encode empty trailing
            // denotator groups in ArtiPaths, but our parsing rules
            // don't forbid them.
            "my_key_path+dino@",
            "my_key_path+@",
        ];

        const BAD_FIRST_CHAR_ARTI_PATHS: &[&str] = &["-hs_client", "-"];

        const DISALLOWED_CHAR_ARTI_PATHS: &[(&str, char)] = &[
            ("client?", '?'),
            ("no spaces please", ' '),
            ("client٣¾", '٣'),
            ("clientß", 'ß'),
            // Invalid paths: the main component of the path
            // must be separated from the denotator groups by a `+` character
            ("my_key_path@", '@'),
            ("my_key_path@dino+saur", '@'),
        ];

        const EMPTY_PATH_COMPONENT: &[&str] =
            &["/////", "/alice/bob", "alice//bob", "alice/bob/", "/"];

        for path in chain!(VALID_ARTI_PATH_COMPONENTS, VALID_ARTI_PATHS) {
            assert_ok!(ArtiPath, path);
        }

        for (path, bad_char) in DISALLOWED_CHAR_ARTI_PATHS {
            assert_err(
                path,
                ArtiPathSyntaxError::Slug(BadSlug::BadCharacter(*bad_char)),
            );
        }

        for path in BAD_FIRST_CHAR_ARTI_PATHS {
            assert_err(
                path,
                ArtiPathSyntaxError::Slug(BadSlug::BadFirstCharacter(path.chars().next().unwrap())),
            );
        }

        for path in EMPTY_PATH_COMPONENT {
            assert_err(
                path,
                ArtiPathSyntaxError::Slug(BadSlug::EmptySlugNotAllowed),
            );
        }

        const SEP: char = PATH_SEP;
        // This is a valid ArtiPath, but not a valid Slug
        let path = format!("a{SEP}client{SEP}key+private");
        assert_ok!(ArtiPath, path);

        const PATH_WITH_TRAVERSAL: &str = "alice/../bob";
        assert_err(
            PATH_WITH_TRAVERSAL,
            ArtiPathSyntaxError::Slug(BadSlug::BadCharacter('.')),
        );

        const REL_PATH: &str = "./bob";
        assert_err(
            REL_PATH,
            ArtiPathSyntaxError::Slug(BadSlug::BadCharacter('.')),
        );

        const EMPTY_DENOTATOR: &str = "c++";
        assert_err(
            EMPTY_DENOTATOR,
            ArtiPathSyntaxError::Slug(BadSlug::EmptySlugNotAllowed),
        );
    }

    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn arti_path_with_denotator() {
        const VALID_ARTI_DENOTATORS: &[&str] = &[
            "foo",
            "one_two_three-f0ur",
            "1-2-3-",
            "1-2-3_",
            "1-2-3",
            "_1-2-3",
            "1-2-3",
        ];

        const BAD_OUTER_CHAR_DENOTATORS: &[&str] = &["-1-2-3"];

        for denotator in VALID_ARTI_DENOTATORS {
            let path = format!("foo/bar/qux+{denotator}");
            assert_ok!(ArtiPath, path);
        }

        for denotator in BAD_OUTER_CHAR_DENOTATORS {
            let path = format!("foo/bar/qux+{denotator}");

            assert_err(
                &path,
                ArtiPathSyntaxError::Slug(BadSlug::BadFirstCharacter(
                    denotator.chars().next().unwrap(),
                )),
            );
        }

        // An ArtiPath with multiple denotators
        let path = format!(
            "foo/bar/qux+{}+{}+foo",
            VALID_ARTI_DENOTATORS[0], VALID_ARTI_DENOTATORS[1]
        );
        assert_ok!(ArtiPath, path);

        // An invalid ArtiPath with multiple valid denotators and
        // an empty (invalid) denotator
        let path = format!(
            "foo/bar/qux+{}+{}+foo+",
            VALID_ARTI_DENOTATORS[0], VALID_ARTI_DENOTATORS[1]
        );
        assert_err(
            &path,
            ArtiPathSyntaxError::Slug(BadSlug::EmptySlugNotAllowed),
        );
    }

    #[test]
    fn substring() {
        const KEY_PATH: &str = "hello";
        let path = ArtiPath::new(KEY_PATH.to_string()).unwrap();

        assert_eq!(path.substring(&(0..1).into()).unwrap(), "h");
        assert_eq!(path.substring(&(2..KEY_PATH.len()).into()).unwrap(), "llo");
        assert_eq!(
            path.substring(&(0..KEY_PATH.len()).into()).unwrap(),
            "hello"
        );
        assert_eq!(path.substring(&(0..KEY_PATH.len() + 1).into()), None);
        assert_eq!(path.substring(&(0..0).into()).unwrap(), "");
    }
}