1
//! The [`KeySpecifier`] trait and its implementations.
2

            
3
use std::collections::BTreeMap;
4
use std::fmt::{self, Debug, Display};
5
use std::ops::Range;
6
use std::result::Result as StdResult;
7
use std::str::FromStr;
8

            
9
use derive_more::From;
10
use safelog::DisplayRedacted as _;
11
use thiserror::Error;
12
use tor_error::{Bug, internal, into_internal};
13
use tor_hscrypto::pk::{HSID_ONION_SUFFIX, HsId, HsIdParseError};
14
use tor_hscrypto::time::TimePeriod;
15
use tor_persist::hsnickname::HsNickname;
16
use tor_persist::slug::Slug;
17

            
18
use crate::{ArtiPath, ArtiPathSyntaxError};
19

            
20
// #[doc(hidden)] applied at crate toplevel
21
#[macro_use]
22
pub mod derive;
23

            
24
/// The identifier of a key.
25
#[derive(Clone, Debug, PartialEq, Eq, Hash, From, derive_more::Display)]
26
#[non_exhaustive]
27
pub enum KeyPath {
28
    /// An Arti key path.
29
    Arti(ArtiPath),
30
    /// A C-Tor key path.
31
    CTor(CTorPath),
32
}
33

            
34
/// A range specifying a substring of a [`KeyPath`].
35
#[derive(Clone, Debug, PartialEq, Eq, Hash, From)]
36
pub struct ArtiPathRange(pub(crate) Range<usize>);
37

            
38
impl ArtiPath {
39
    /// Check whether this `ArtiPath` matches the specified [`KeyPathPattern`].
40
    ///
41
    /// If the `ArtiPath` matches the pattern, this returns the ranges that match its dynamic parts.
42
    ///
43
    /// ### Example
44
    /// ```
45
    /// # use tor_keymgr::{ArtiPath, KeyPath, KeyPathPattern, ArtiPathSyntaxError};
46
    /// # fn demo() -> Result<(), ArtiPathSyntaxError> {
47
    /// let path = ArtiPath::new("foo_bar_baz_1".into())?;
48
    /// let pattern = KeyPathPattern::Arti("*_bar_baz_*".into());
49
    /// let matches = path.matches(&pattern).unwrap();
50
    ///
51
    /// assert_eq!(matches.len(), 2);
52
    /// assert_eq!(path.substring(&matches[0]), Some("foo"));
53
    /// assert_eq!(path.substring(&matches[1]), Some("1"));
54
    /// # Ok(())
55
    /// # }
56
    /// #
57
    /// # demo().unwrap();
58
    /// ```
59
5406
    pub fn matches(&self, pat: &KeyPathPattern) -> Option<Vec<ArtiPathRange>> {
60
        use KeyPathPattern::*;
61

            
62
5406
        let pattern: &str = match pat {
63
5406
            Arti(pat) => pat.as_ref(),
64
            _ => return None,
65
        };
66

            
67
5406
        glob_match::glob_match_with_captures(pattern, self.as_ref())
68
10917
            .map(|res| res.into_iter().map(|r| r.into()).collect())
69
5406
    }
70
}
71

            
72
impl KeyPath {
73
    /// Check whether this `KeyPath` matches the specified [`KeyPathPattern`].
74
    ///
75
    /// Returns `true` if the `KeyPath` matches the pattern.
76
    ///
77
    /// ### Example
78
    /// ```
79
    /// # use tor_keymgr::{ArtiPath, KeyPath, KeyPathPattern, ArtiPathSyntaxError};
80
    /// # fn demo() -> Result<(), ArtiPathSyntaxError> {
81
    /// let path = KeyPath::Arti(ArtiPath::new("foo_bar_baz_1".into())?);
82
    /// let pattern = KeyPathPattern::Arti("*_bar_baz_*".into());
83
    /// assert!(path.matches(&pattern));
84
    /// # Ok(())
85
    /// # }
86
    /// #
87
    /// # demo().unwrap();
88
    /// ```
89
6006
    pub fn matches(&self, pat: &KeyPathPattern) -> bool {
90
        use KeyPathPattern::*;
91

            
92
6006
        match (self, pat) {
93
5406
            (KeyPath::Arti(p), Arti(_)) => p.matches(pat).is_some(),
94
            (KeyPath::CTor(p), CTor(pat)) if p == pat => true,
95
600
            _ => false,
96
        }
97
6006
    }
98

            
99
    // TODO: rewrite these getters using derive_adhoc if KeyPath grows more variants.
100

            
101
    /// Return the underlying [`ArtiPath`], if this is a `KeyPath::Arti`.
102
    pub fn arti(&self) -> Option<&ArtiPath> {
103
        match self {
104
            KeyPath::Arti(arti) => Some(arti),
105
            KeyPath::CTor(_) => None,
106
        }
107
    }
108

            
109
    /// Return the underlying [`CTorPath`], if this is a `KeyPath::CTor`.
110
8
    pub fn ctor(&self) -> Option<&CTorPath> {
111
8
        match self {
112
            KeyPath::Arti(_) => None,
113
8
            KeyPath::CTor(ctor) => Some(ctor),
114
        }
115
8
    }
116
}
117

            
118
/// A pattern specifying some or all of a kind of key
119
///
120
/// Generally implemented on `SomeKeySpecifierPattern` by
121
/// applying
122
/// [`#[derive_deftly(KeySpecifier)`](crate::derive_deftly_template_KeySpecifier)
123
/// to `SomeKeySpecifier`.
124
pub trait KeySpecifierPattern {
125
    /// Obtain a pattern template that matches all keys of this type.
126
    fn new_any() -> Self
127
    where
128
        Self: Sized;
129

            
130
    /// Get a [`KeyPathPattern`] that can match the [`ArtiPath`]s
131
    /// of some or all the keys of this type.
132
    fn arti_pattern(&self) -> Result<KeyPathPattern, Bug>;
133
}
134

            
135
/// An error while attempting to extract information about a key given its path
136
///
137
/// For example, from a [`KeyPathInfoExtractor`].
138
///
139
/// See also `crate::keystore::arti::MalformedPathError`,
140
/// which occurs at a lower level.
141
///
142
// Note: Currently, all KeyPathErrors (except Unrecognized and Bug) are only returned from
143
// functions that parse ArtiPaths and/or ArtiPath denotators, so their context contains an
144
// `ArtiPath` rather than a `KeyPath` (i.e. PatternNotMatched, InvalidArtiPath,
145
// InvalidKeyPathComponent value can only happen if we're dealing with an ArtiPath).
146
//
147
// For now this is alright, but we might want to rethink this error enum (for example, a better
148
// idea might be to create an ArtiPathError { path: ArtiPath, kind: ArtiPathErrorKind } error type
149
// and move PatternNotMatched, InvalidArtiPath, InvalidKeyPathComponentValue to the new
150
// ArtiPathErrorKind enum.
151
#[derive(Debug, Clone, thiserror::Error)]
152
#[non_exhaustive]
153
pub enum KeyPathError {
154
    /// The path did not match the expected pattern.
155
    #[error("Path does not match expected pattern")]
156
    PatternNotMatched(ArtiPath),
157

            
158
    /// The path is not recognized.
159
    ///
160
    /// Returned by [`KeyMgr::describe`](crate::KeyMgr::describe) when none of its
161
    /// [`KeyPathInfoExtractor`]s is able to parse the specified [`KeyPath`].
162
    #[error("Unrecognized path: {0}")]
163
    Unrecognized(KeyPath),
164

            
165
    /// Found an invalid [`ArtiPath`], which is syntactically invalid on its face
166
    #[error("ArtiPath {path} is invalid")]
167
    InvalidArtiPath {
168
        /// What was wrong with the value
169
        #[source]
170
        error: ArtiPathSyntaxError,
171
        /// The offending `ArtiPath`.
172
        path: ArtiPath,
173
    },
174

            
175
    /// An invalid key path component value string was encountered
176
    ///
177
    /// When attempting to interpret a key path, one of the elements in the path
178
    /// contained a string value which wasn't a legitimate representation of the
179
    /// type of data expected there for this kind of key.
180
    ///
181
    /// (But the key path is in the proper character set.)
182
    #[error("invalid string value for element of key path")]
183
    InvalidKeyPathComponentValue {
184
        /// What was wrong with the value
185
        #[source]
186
        error: InvalidKeyPathComponentValue,
187
        /// The name of the "key" (what data we were extracting)
188
        ///
189
        /// Should be valid Rust identifier syntax.
190
        key: String,
191
        /// The `ArtiPath` of the key.
192
        path: ArtiPath,
193
        /// The substring of the `ArtiPath` that couldn't be parsed.
194
        value: Slug,
195
    },
196

            
197
    /// An internal error.
198
    #[error("Internal error")]
199
    Bug(#[from] tor_error::Bug),
200
}
201

            
202
/// Error to be returned by `KeySpecifierComponent::from_slug` implementations
203
///
204
/// Currently this error contains little information,
205
/// but the context and value are provided in
206
/// [`KeyPathError::InvalidKeyPathComponentValue`].
207
#[derive(Error, Clone, Debug)]
208
#[non_exhaustive]
209
pub enum InvalidKeyPathComponentValue {
210
    /// Found an invalid slug.
211
    ///
212
    /// The inner string should be a description of what is wrong with the slug.
213
    /// It should not say that the keystore was corrupted,
214
    /// (keystore corruption errors are reported using higher level
215
    /// [`KeystoreCorruptionError`s](crate::KeystoreCorruptionError)),
216
    /// or where the information came from (the context is encoded in the
217
    /// enclosing [`KeyPathError::InvalidKeyPathComponentValue`] error).
218
    #[error("{0}")]
219
    Slug(String),
220

            
221
    /// An internal error.
222
    ///
223
    /// The [`KeySpecifierComponentViaDisplayFromStr`] trait maps any errors returned by the
224
    /// [`FromStr`] implementation of the implementing type to this variant.
225
    #[error("Internal error")]
226
    Bug(#[from] tor_error::Bug),
227
}
228

            
229
/// Information about a [`KeyPath`].
230
///
231
/// The information is extracted from the [`KeyPath`] itself
232
/// (_not_ from the key data) by a [`KeyPathInfoExtractor`].
233
//
234
// TODO  maybe the getters should be combined with the builder, or something?
235
#[derive(Debug, Clone, PartialEq, derive_builder::Builder, amplify::Getters)]
236
pub struct KeyPathInfo {
237
    /// A human-readable summary string describing what the [`KeyPath`] is for.
238
    ///
239
    /// This should *not* recapitulate information in the `extra_info`.
240
    summary: String,
241
    /// The key role, ie its official name in the Tor Protocols.
242
    ///
243
    /// This should usually start with `KS_`.
244
    //
245
    // TODO (#1195): see the comment for #[deftly(role)] in derive.rs
246
    role: String,
247
    /// Additional information, in the form of key-value pairs.
248
    ///
249
    /// This will contain human-readable information that describes the individual
250
    /// components of a KeyPath. For example, for the [`ArtiPath`]
251
    /// `hs/foo/KS_hs_id.expanded_ed25519_private`, the extra information could
252
    /// be `("kind", "service)`, `("nickname", "foo")`, etc.
253
    #[builder(default, setter(custom))]
254
    extra_info: BTreeMap<String, String>,
255
}
256

            
257
impl KeyPathInfo {
258
    /// Start to build a [`KeyPathInfo`]: return a fresh [`KeyPathInfoBuilder`]
259
8
    pub fn builder() -> KeyPathInfoBuilder {
260
8
        KeyPathInfoBuilder::default()
261
8
    }
262
}
263

            
264
impl KeyPathInfoBuilder {
265
    /// Initialize the additional information of this builder with the specified values.
266
    ///
267
    /// Erases the preexisting `extra_info`.
268
6
    pub fn set_all_extra_info(
269
6
        &mut self,
270
6
        all_extra_info: impl Iterator<Item = (String, String)>,
271
6
    ) -> &mut Self {
272
6
        self.extra_info = Some(all_extra_info.collect());
273
6
        self
274
6
    }
275

            
276
    /// Append the specified key-value pair to the `extra_info`.
277
    ///
278
    /// The preexisting `extra_info` is preserved.
279
822
    pub fn extra_info(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
280
822
        let extra_info = self.extra_info.get_or_insert(Default::default());
281
822
        extra_info.insert(key.into(), value.into());
282
822
        self
283
822
    }
284
}
285

            
286
/// A trait for extracting info out of a [`KeyPath`]s.
287
///
288
/// This trait is used by [`KeyMgr::describe`](crate::KeyMgr::describe)
289
/// to extract information out of [`KeyPath`]s.
290
pub trait KeyPathInfoExtractor: Send + Sync {
291
    /// Describe the specified `path`.
292
    fn describe(&self, path: &KeyPath) -> StdResult<KeyPathInfo, KeyPathError>;
293
}
294

            
295
/// Register a [`KeyPathInfoExtractor`] for use with [`KeyMgr`](crate::KeyMgr).
296
#[macro_export]
297
macro_rules! register_key_info_extractor {
298
    ($kv:expr) => {{
299
        $crate::inventory::submit!(&$kv as &dyn $crate::KeyPathInfoExtractor);
300
    }};
301
}
302

            
303
/// A pattern that can be used to match [`ArtiPath`]s or [`CTorPath`]s.
304
///
305
/// Create a new `KeyPathPattern`.
306
///
307
/// ## Syntax
308
///
309
/// NOTE: this table is copied verbatim from the [`glob-match`] docs.
310
///
311
/// | Syntax  | Meaning                                                                                                                                                                                             |
312
/// | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
313
/// | `?`     | Matches any single character.                                                                                                                                                                       |
314
/// | `*`     | Matches zero or more characters, except for path separators (e.g. `/`).                                                                                                                             |
315
/// | `**`    | Matches zero or more characters, including path separators. Must match a complete path segment (i.e. followed by a `/` or the end of the pattern).                                                  |
316
/// | `[ab]`  | Matches one of the characters contained in the brackets. Character ranges, e.g. `[a-z]` are also supported. Use `[!ab]` or `[^ab]` to match any character _except_ those contained in the brackets. |
317
/// | `{a,b}` | Matches one of the patterns contained in the braces. Any of the wildcard characters can be used in the sub-patterns. Braces may be nested up to 10 levels deep.                                     |
318
/// | `!`     | When at the start of the glob, this negates the result. Multiple `!` characters negate the glob multiple times.                                                                                     |
319
/// | `\`     | A backslash character may be used to escape any of the above special characters.                                                                                                                    |
320
///
321
/// [`glob-match`]: https://crates.io/crates/glob-match
322
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
323
#[non_exhaustive]
324
pub enum KeyPathPattern {
325
    /// A pattern for matching [`ArtiPath`]s.
326
    Arti(String),
327
    /// A pattern for matching [`CTorPath`]s.
328
    CTor(CTorPath),
329
}
330

            
331
/// The path of a key in the C Tor key store.
332
#[derive(Clone, Debug, PartialEq, Eq, Hash, derive_more::Display)] //
333
#[non_exhaustive]
334
pub enum CTorPath {
335
    /// A client descriptor encryption key, to be looked up in ClientOnionAuthDir.
336
    ///
337
    /// Represents an entry in C Tor's `ClientOnionAuthDir`.
338
    ///
339
    /// We can't statically know exactly *which* entry has the key for this `HsId`
340
    /// (we'd need to read and parse each file from `ClientOnionAuthDir` to find out).
341
    //
342
    // TODO: Perhaps we should redact this sometimes.
343
    #[display("ClientHsDescEncKey({})", _0.display_unredacted())]
344
    ClientHsDescEncKey(HsId),
345
    /// A service key path.
346
    #[display("{path}")]
347
    Service {
348
        /// The nickname of the service,
349
        nickname: HsNickname,
350
        /// The relative path of this key.
351
        path: CTorServicePath,
352
    },
353
}
354

            
355
/// The relative path in a C Tor key store.
356
#[derive(Clone, Debug, PartialEq, Eq, Hash, derive_more::Display)] //
357
#[non_exhaustive]
358
pub enum CTorServicePath {
359
    /// C Tor's `HiddenServiceDirectory/hs_ed25519_public_key`.
360
    #[display("hs_ed25519_public_key")]
361
    PublicKey,
362
    /// C Tor's `HiddenServiceDirectory/hs_ed25519_secret_key`.
363
    #[display("hs_ed25519_secret_key")]
364
    PrivateKey,
365
}
366

            
367
impl CTorPath {
368
    /// Create a CTorPath that represents a service key.
369
    pub fn service(nickname: HsNickname, path: CTorServicePath) -> Self {
370
        Self::Service { nickname, path }
371
    }
372

            
373
    /// Create a CTorPath that represents a client authorization key.
374
    pub fn client(hsid: HsId) -> Self {
375
        Self::ClientHsDescEncKey(hsid)
376
    }
377
}
378

            
379
/// The "specifier" of a key, which identifies an instance of a key.
380
///
381
/// [`KeySpecifier::arti_path()`] should uniquely identify an instance of a key.
382
pub trait KeySpecifier {
383
    /// The location of the key in the Arti key store.
384
    ///
385
    /// This also acts as a unique identifier for a specific key instance.
386
    fn arti_path(&self) -> StdResult<ArtiPath, ArtiPathUnavailableError>;
387

            
388
    /// The location of the key in the C Tor key store (if supported).
389
    ///
390
    /// This function should return `None` for keys that are recognized by Arti's key stores, but
391
    /// not by C Tor's key store (such as `HsClientIntroAuthKeypair`).
392
    fn ctor_path(&self) -> Option<CTorPath>;
393

            
394
    /// If this is the specifier for a public key, the specifier for
395
    /// the corresponding (secret) keypair from which it can be derived
396
    fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>>;
397
}
398

            
399
/// A trait for serializing and deserializing specific types of [`Slug`]s.
400
///
401
/// A `KeySpecifierComponent` is a specific kind of `Slug`. A `KeySpecifierComponent` is
402
/// always a valid `Slug`, but may have a more restricted charset, or more specific
403
/// validation rules. A `Slug` is not always a valid `KeySpecifierComponent`
404
/// instance.
405
///
406
/// If you are deriving [`DefaultKeySpecifier`](crate::derive_deftly_template_KeySpecifier) for a
407
/// struct, all of its fields must implement this trait.
408
///
409
/// If you are implementing [`KeySpecifier`] and [`KeyPathInfoExtractor`] manually rather than by
410
/// deriving `DefaultKeySpecifier`, you do not need to implement this trait.
411
pub trait KeySpecifierComponent {
412
    /// Return the [`Slug`] representation of this type.
413
    fn to_slug(&self) -> Result<Slug, Bug>;
414
    /// Try to convert `s` into an object of this type.
415
    fn from_slug(s: &Slug) -> StdResult<Self, InvalidKeyPathComponentValue>
416
    where
417
        Self: Sized;
418
    /// Display the value in a human-meaningful representation
419
    ///
420
    /// The output should be a single line (without trailing full stop).
421
    fn fmt_pretty(&self, f: &mut fmt::Formatter) -> fmt::Result;
422
}
423

            
424
/// An error returned by a [`KeySpecifier`].
425
///
426
/// The putative `KeySpecifier` might be simply invalid,
427
/// or it might be being used in an inappropriate context.
428
#[derive(Error, Debug, Clone)]
429
#[non_exhaustive]
430
pub enum ArtiPathUnavailableError {
431
    /// An internal error.
432
    #[error("Internal error")]
433
    Bug(#[from] tor_error::Bug),
434

            
435
    /// An error returned by a [`KeySpecifier`] that does not have an [`ArtiPath`].
436
    ///
437
    /// This is returned, for example, by [`CTorPath`]'s [`KeySpecifier::arti_path`]
438
    /// implementation.
439
    #[error("ArtiPath unavailable")]
440
    ArtiPathUnavailable,
441
}
442

            
443
impl KeySpecifier for ArtiPath {
444
1490
    fn arti_path(&self) -> StdResult<ArtiPath, ArtiPathUnavailableError> {
445
1490
        Ok(self.clone())
446
1490
    }
447

            
448
    fn ctor_path(&self) -> Option<CTorPath> {
449
        None
450
    }
451

            
452
    fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>> {
453
        None
454
    }
455
}
456

            
457
impl KeySpecifier for CTorPath {
458
    fn arti_path(&self) -> StdResult<ArtiPath, ArtiPathUnavailableError> {
459
        Err(ArtiPathUnavailableError::ArtiPathUnavailable)
460
    }
461

            
462
904
    fn ctor_path(&self) -> Option<CTorPath> {
463
904
        Some(self.clone())
464
904
    }
465

            
466
    fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>> {
467
        None
468
    }
469
}
470

            
471
impl KeySpecifier for KeyPath {
472
1462
    fn arti_path(&self) -> StdResult<ArtiPath, ArtiPathUnavailableError> {
473
1462
        match self {
474
1462
            KeyPath::Arti(p) => p.arti_path(),
475
            KeyPath::CTor(p) => p.arti_path(),
476
        }
477
1462
    }
478

            
479
    fn ctor_path(&self) -> Option<CTorPath> {
480
        match self {
481
            KeyPath::Arti(p) => p.ctor_path(),
482
            KeyPath::CTor(p) => p.ctor_path(),
483
        }
484
    }
485

            
486
    fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>> {
487
        None
488
    }
489
}
490

            
491
impl KeySpecifierComponent for TimePeriod {
492
9293
    fn to_slug(&self) -> Result<Slug, Bug> {
493
9293
        Slug::new(format!(
494
9293
            "{}_{}_{}",
495
9293
            self.interval_num(),
496
9293
            self.length(),
497
9293
            self.epoch_offset_in_sec()
498
        ))
499
9293
        .map_err(into_internal!("TP formatting went wrong"))
500
9293
    }
501

            
502
232
    fn from_slug(s: &Slug) -> StdResult<Self, InvalidKeyPathComponentValue>
503
232
    where
504
232
        Self: Sized,
505
    {
506
        use itertools::Itertools;
507

            
508
232
        let s = s.to_string();
509
        #[allow(clippy::redundant_closure)] // the closure makes things slightly more readable
510
234
        let err_ctx = |e: &str| InvalidKeyPathComponentValue::Slug(e.to_string());
511
232
        let (interval, len, offset) = s
512
232
            .split('_')
513
232
            .collect_tuple()
514
234
            .ok_or_else(|| err_ctx("invalid number of subcomponents"))?;
515

            
516
228
        let length = len.parse().map_err(|_| err_ctx("invalid length"))?;
517
228
        let interval_num = interval
518
228
            .parse()
519
228
            .map_err(|_| err_ctx("invalid interval_num"))?;
520
228
        let offset_in_sec = offset
521
228
            .parse()
522
228
            .map_err(|_| err_ctx("invalid offset_in_sec"))?;
523

            
524
228
        Ok(TimePeriod::from_parts(length, interval_num, offset_in_sec))
525
232
    }
526

            
527
152
    fn fmt_pretty(&self, f: &mut fmt::Formatter) -> fmt::Result {
528
152
        Display::fmt(&self, f)
529
152
    }
530
}
531

            
532
/// Implement [`KeySpecifierComponent`] in terms of [`Display`] and [`FromStr`] (helper trait)
533
///
534
/// The default [`from_slug`](KeySpecifierComponent::from_slug) implementation maps any errors
535
/// returned from [`FromStr`] to [`InvalidKeyPathComponentValue::Bug`].
536
/// Key specifier components that cannot readily be parsed from a string should have a bespoke
537
/// [`from_slug`](KeySpecifierComponent::from_slug) implementation, and
538
/// return more descriptive errors through [`InvalidKeyPathComponentValue::Slug`].
539
pub trait KeySpecifierComponentViaDisplayFromStr: Display + FromStr {}
540
impl<T: KeySpecifierComponentViaDisplayFromStr> KeySpecifierComponent for T {
541
2412
    fn to_slug(&self) -> Result<Slug, Bug> {
542
2412
        self.to_string()
543
2412
            .try_into()
544
2412
            .map_err(into_internal!("Display generated bad Slug"))
545
2412
    }
546
2246
    fn from_slug(s: &Slug) -> Result<Self, InvalidKeyPathComponentValue>
547
2246
    where
548
2246
        Self: Sized,
549
    {
550
2246
        s.as_str()
551
2246
            .parse()
552
2246
            .map_err(|_| internal!("slug cannot be parsed as component").into())
553
2246
    }
554
368
    fn fmt_pretty(&self, f: &mut fmt::Formatter) -> fmt::Result {
555
368
        Display::fmt(self, f)
556
368
    }
557
}
558

            
559
impl KeySpecifierComponentViaDisplayFromStr for HsNickname {}
560

            
561
impl KeySpecifierComponent for HsId {
562
652
    fn to_slug(&self) -> StdResult<Slug, Bug> {
563
        // We can't implement KeySpecifierComponentViaDisplayFromStr for HsId,
564
        // because its Display impl contains the `.onion` suffix, and Slugs can't
565
        // contain `.`.
566
652
        let hsid = self.display_unredacted().to_string();
567
652
        let hsid_slug = hsid
568
652
            .strip_suffix(HSID_ONION_SUFFIX)
569
652
            .ok_or_else(|| internal!("HsId Display impl missing .onion suffix?!"))?;
570
652
        hsid_slug
571
652
            .to_owned()
572
652
            .try_into()
573
652
            .map_err(into_internal!("Display generated bad Slug"))
574
652
    }
575

            
576
102
    fn from_slug(s: &Slug) -> StdResult<Self, InvalidKeyPathComponentValue>
577
102
    where
578
102
        Self: Sized,
579
    {
580
        // Note: HsId::from_str expects the string to have a .onion suffix,
581
        // but the string representation of our slug doesn't have it
582
        // (because we manually strip it away, see to_slug()).
583
        //
584
        // We have to manually add it for this to work.
585
        //
586
        // TODO: HsId should have some facilities for converting base32 HsIds (sans suffix)
587
        // to and from string.
588
102
        let onion = format!("{}{HSID_ONION_SUFFIX}", s.as_str());
589

            
590
102
        onion
591
102
            .parse()
592
102
            .map_err(|e: HsIdParseError| InvalidKeyPathComponentValue::Slug(e.to_string()))
593
102
    }
594

            
595
100
    fn fmt_pretty(&self, f: &mut fmt::Formatter) -> fmt::Result {
596
100
        Display::fmt(&self.display_redacted(), f)
597
100
    }
598
}
599

            
600
/// Wrapper for `KeySpecifierComponent` that `Displays` via `fmt_pretty`
601
struct KeySpecifierComponentPrettyHelper<'c>(&'c dyn KeySpecifierComponent);
602

            
603
impl Display for KeySpecifierComponentPrettyHelper<'_> {
604
812
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
605
812
        KeySpecifierComponent::fmt_pretty(self.0, f)
606
812
    }
607
}
608

            
609
/// The "specifier" of a key certificate, which identifies an instance of a cert,
610
/// as well as its signing and subject keys.
611
///
612
/// Certificates can only be fetched from Arti key stores
613
/// (we will not support loading certs from C Tor's key directory)
614
pub trait KeyCertificateSpecifier {
615
    /// The denotators of the certificate.
616
    ///
617
    /// Used by `KeyMgr` to derive the `ArtiPath` of the certificate.
618
    /// The `ArtiPath` of a certificate is obtained
619
    /// by concatenating the `ArtiPath` of the subject key with the
620
    /// denotators provided by this function,
621
    /// with a `+` between the `ArtiPath` of the subject key and
622
    /// the denotators (the `+` is omitted if there are no denotators).
623
    fn cert_denotators(&self) -> Vec<&dyn KeySpecifierComponent>;
624
    /// The key specifier of the signing key.
625
    ///
626
    /// Returns `None` if the signing key should not be retrieved from the keystore.
627
    ///
628
    /// Note: a return value of `None` means the signing key will be provided
629
    /// as an argument to the `KeyMgr` accessor this `KeyCertificateSpecifier`
630
    /// will be used with.
631
    fn signing_key_specifier(&self) -> Option<&dyn KeySpecifier>;
632
    /// The key specifier of the subject key.
633
    fn subject_key_specifier(&self) -> &dyn KeySpecifier;
634
}
635

            
636
#[cfg(test)]
637
mod test {
638
    // @@ begin test lint list maintained by maint/add_warning @@
639
    #![allow(clippy::bool_assert_comparison)]
640
    #![allow(clippy::clone_on_copy)]
641
    #![allow(clippy::dbg_macro)]
642
    #![allow(clippy::mixed_attributes_style)]
643
    #![allow(clippy::print_stderr)]
644
    #![allow(clippy::print_stdout)]
645
    #![allow(clippy::single_char_pattern)]
646
    #![allow(clippy::unwrap_used)]
647
    #![allow(clippy::unchecked_duration_subtraction)]
648
    #![allow(clippy::useless_vec)]
649
    #![allow(clippy::needless_pass_by_value)]
650
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
651
    use super::*;
652

            
653
    use crate::test_utils::check_key_specifier;
654
    use derive_deftly::Deftly;
655
    use humantime::parse_rfc3339;
656
    use itertools::Itertools;
657
    use serde::{Deserialize, Serialize};
658
    use std::fmt::Debug;
659
    use std::time::Duration;
660

            
661
    impl KeySpecifierComponentViaDisplayFromStr for usize {}
662
    impl KeySpecifierComponentViaDisplayFromStr for String {}
663

            
664
    // This impl probably shouldn't be made non-test, since it produces longer paths
665
    // than is necessary.  `t`/`f` would be better representation.  But it's fine for tests.
666
    impl KeySpecifierComponentViaDisplayFromStr for bool {}
667

            
668
    fn test_time_period() -> TimePeriod {
669
        TimePeriod::new(
670
            Duration::from_secs(86400),
671
            parse_rfc3339("2020-09-15T00:00:00Z").unwrap(),
672
            Duration::from_secs(3600),
673
        )
674
        .unwrap()
675
    }
676

            
677
    #[test]
678
    fn pretty_time_period() {
679
        let tp = test_time_period();
680
        assert_eq!(
681
            KeySpecifierComponentPrettyHelper(&tp).to_string(),
682
            "#18519 2020-09-14T01:00:00Z..+24:00",
683
        );
684
    }
685

            
686
    #[test]
687
    fn serde() {
688
        // TODO: clone-and-hack with tor_hsservice::::nickname::test::serde
689
        // perhaps there should be some utility in tor-basic-utils for testing
690
        // validated string newtypes, or something
691
        #[derive(Serialize, Deserialize, Debug)]
692
        struct T {
693
            n: Slug,
694
        }
695
        let j = serde_json::from_str(r#"{ "n": "x" }"#).unwrap();
696
        let t: T = serde_json::from_value(j).unwrap();
697
        assert_eq!(&t.n.to_string(), "x");
698

            
699
        assert_eq!(&serde_json::to_string(&t).unwrap(), r#"{"n":"x"}"#);
700

            
701
        let j = serde_json::from_str(r#"{ "n": "!" }"#).unwrap();
702
        let e = serde_json::from_value::<T>(j).unwrap_err();
703
        assert!(
704
            e.to_string()
705
                .contains("character '!' (U+0021) is not allowed"),
706
            "wrong msg {e:?}"
707
        );
708
    }
709

            
710
    #[test]
711
    fn define_key_specifier_with_fields_and_denotator() {
712
        let tp = test_time_period();
713

            
714
        #[derive(Deftly, Debug, PartialEq)]
715
        #[derive_deftly(KeySpecifier)]
716
        #[deftly(prefix = "encabulator")]
717
        #[deftly(role = "marzlevane")]
718
        #[deftly(summary = "test key")]
719
        struct TestSpecifier {
720
            // The remaining fields
721
            kind: String,
722
            base: String,
723
            casing: String,
724
            #[deftly(denotator)]
725
            count: usize,
726
            #[deftly(denotator)]
727
            tp: TimePeriod,
728
        }
729

            
730
        let key_spec = TestSpecifier {
731
            kind: "hydrocoptic".into(),
732
            base: "waneshaft".into(),
733
            casing: "logarithmic".into(),
734
            count: 6,
735
            tp,
736
        };
737

            
738
        check_key_specifier(
739
            &key_spec,
740
            "encabulator/hydrocoptic/waneshaft/logarithmic/marzlevane+6+18519_1440_3600",
741
        );
742

            
743
        let info = TestSpecifierInfoExtractor
744
            .describe(&KeyPath::Arti(key_spec.arti_path().unwrap()))
745
            .unwrap();
746

            
747
        assert_eq!(
748
            format!("{info:#?}"),
749
            r##"
750
KeyPathInfo {
751
    summary: "test key",
752
    role: "marzlevane",
753
    extra_info: {
754
        "base": "waneshaft",
755
        "casing": "logarithmic",
756
        "count": "6",
757
        "kind": "hydrocoptic",
758
        "tp": "#18519 2020-09-14T01:00:00Z..+24:00",
759
    },
760
2
}
761
2
            "##
762
2
            .trim()
763
        );
764
2
    }
765

            
766
    #[test]
767
2
    fn define_key_specifier_no_fields() {
768
        #[derive(Deftly, Debug, PartialEq)]
769
        #[derive_deftly(KeySpecifier)]
770
        #[deftly(prefix = "encabulator")]
771
        #[deftly(role = "marzlevane")]
772
        #[deftly(summary = "test key")]
773
        struct TestSpecifier {}
774

            
775
2
        let key_spec = TestSpecifier {};
776

            
777
2
        check_key_specifier(&key_spec, "encabulator/marzlevane");
778

            
779
2
        assert_eq!(
780
2
            TestSpecifierPattern {}.arti_pattern().unwrap(),
781
2
            KeyPathPattern::Arti("encabulator/marzlevane".into())
782
        );
783
2
    }
784

            
785
    #[test]
786
2
    fn define_key_specifier_with_denotator() {
787
        #[derive(Deftly, Debug, PartialEq)]
788
        #[derive_deftly(KeySpecifier)]
789
        #[deftly(prefix = "encabulator")]
790
        #[deftly(role = "marzlevane")]
791
        #[deftly(summary = "test key")]
792
        struct TestSpecifier {
793
            #[deftly(denotator)]
794
            count: usize,
795
        }
796

            
797
2
        let key_spec = TestSpecifier { count: 6 };
798

            
799
2
        check_key_specifier(&key_spec, "encabulator/marzlevane+6");
800

            
801
2
        assert_eq!(
802
2
            TestSpecifierPattern { count: None }.arti_pattern().unwrap(),
803
2
            KeyPathPattern::Arti("encabulator/marzlevane+*".into())
804
        );
805
2
    }
806

            
807
    #[test]
808
2
    fn define_key_specifier_with_fields() {
809
        #[derive(Deftly, Debug, PartialEq)]
810
        #[derive_deftly(KeySpecifier)]
811
        #[deftly(prefix = "encabulator")]
812
        #[deftly(role = "fan")]
813
        #[deftly(summary = "test key")]
814
        struct TestSpecifier {
815
            casing: String,
816
            /// A doc comment.
817
            bearings: String,
818
        }
819

            
820
2
        let key_spec = TestSpecifier {
821
2
            casing: "logarithmic".into(),
822
2
            bearings: "spurving".into(),
823
2
        };
824

            
825
2
        check_key_specifier(&key_spec, "encabulator/logarithmic/spurving/fan");
826

            
827
2
        assert_eq!(
828
2
            TestSpecifierPattern {
829
2
                casing: Some("logarithmic".into()),
830
2
                bearings: Some("prefabulating".into()),
831
2
            }
832
2
            .arti_pattern()
833
2
            .unwrap(),
834
2
            KeyPathPattern::Arti("encabulator/logarithmic/prefabulating/fan".into())
835
        );
836

            
837
2
        assert_eq!(key_spec.ctor_path(), None);
838
2
    }
839

            
840
    #[test]
841
2
    fn define_key_specifier_with_multiple_denotators() {
842
        #[derive(Deftly, Debug, PartialEq)]
843
        #[derive_deftly(KeySpecifier)]
844
        #[deftly(prefix = "encabulator")]
845
        #[deftly(role = "fan")]
846
        #[deftly(summary = "test key")]
847
        struct TestSpecifier {
848
            casing: String,
849
            /// A doc comment.
850
            bearings: String,
851

            
852
            #[deftly(denotator)]
853
            count: usize,
854

            
855
            #[deftly(denotator)]
856
            length: usize,
857

            
858
            #[deftly(denotator)]
859
            kind: String,
860
        }
861

            
862
2
        let key_spec = TestSpecifier {
863
2
            casing: "logarithmic".into(),
864
2
            bearings: "spurving".into(),
865
2
            count: 8,
866
2
            length: 2000,
867
2
            kind: "lunar".into(),
868
2
        };
869

            
870
2
        check_key_specifier(
871
2
            &key_spec,
872
2
            "encabulator/logarithmic/spurving/fan+8+2000+lunar",
873
        );
874

            
875
2
        assert_eq!(
876
2
            TestSpecifierPattern {
877
2
                casing: Some("logarithmic".into()),
878
2
                bearings: Some("prefabulating".into()),
879
2
                ..TestSpecifierPattern::new_any()
880
2
            }
881
2
            .arti_pattern()
882
2
            .unwrap(),
883
2
            KeyPathPattern::Arti("encabulator/logarithmic/prefabulating/fan+*+*+*".into())
884
        );
885
2
    }
886

            
887
    #[test]
888
2
    fn define_key_specifier_role_field() {
889
        #[derive(Deftly, Debug, Eq, PartialEq)]
890
        #[derive_deftly(KeySpecifier)]
891
        #[deftly(prefix = "prefix")]
892
        #[deftly(summary = "test key")]
893
        struct TestSpecifier {
894
            #[deftly(role)]
895
            role: String,
896
            i: usize,
897
            #[deftly(denotator)]
898
            den: bool,
899
        }
900

            
901
2
        check_key_specifier(
902
2
            &TestSpecifier {
903
2
                i: 1,
904
2
                role: "role".to_string(),
905
2
                den: true,
906
2
            },
907
2
            "prefix/1/role+true",
908
        );
909
2
    }
910

            
911
    #[test]
912
2
    fn define_key_specifier_ctor_path() {
913
        #[derive(Deftly, Debug, Eq, PartialEq)]
914
        #[derive_deftly(KeySpecifier)]
915
        #[deftly(prefix = "p")]
916
        #[deftly(role = "r")]
917
        #[deftly(ctor_path = "Self::ctp")]
918
        #[deftly(summary = "test key")]
919
        struct TestSpecifier {
920
            i: usize,
921
        }
922

            
923
        impl TestSpecifier {
924
2
            fn ctp(&self) -> CTorPath {
925
2
                CTorPath::Service {
926
2
                    nickname: HsNickname::from_str("allium-cepa").unwrap(),
927
2
                    path: CTorServicePath::PublicKey,
928
2
                }
929
2
            }
930
        }
931

            
932
2
        let spec = TestSpecifier { i: 42 };
933

            
934
2
        check_key_specifier(&spec, "p/42/r");
935

            
936
2
        assert_eq!(
937
2
            spec.ctor_path(),
938
2
            Some(CTorPath::Service {
939
2
                nickname: HsNickname::from_str("allium-cepa").unwrap(),
940
2
                path: CTorServicePath::PublicKey,
941
2
            }),
942
        );
943
2
    }
944

            
945
    #[test]
946
2
    fn define_key_specifier_fixed_path_component() {
947
        #[derive(Deftly, Debug, Eq, PartialEq)]
948
        #[derive_deftly(KeySpecifier)]
949
        #[deftly(prefix = "prefix")]
950
        #[deftly(role = "role")]
951
        #[deftly(summary = "test key")]
952
        struct TestSpecifier {
953
            x: usize,
954
            #[deftly(fixed_path_component = "fixed")]
955
            z: bool,
956
        }
957

            
958
2
        check_key_specifier(&TestSpecifier { x: 1, z: true }, "prefix/1/fixed/true/role");
959
2
    }
960

            
961
    #[test]
962
2
    fn encode_time_period() {
963
2
        let period = TimePeriod::from_parts(1, 2, 3);
964
2
        let encoded_period = period.to_slug().unwrap();
965

            
966
2
        assert_eq!(encoded_period.to_string(), "2_1_3");
967
2
        assert_eq!(period, TimePeriod::from_slug(&encoded_period).unwrap());
968

            
969
2
        assert!(TimePeriod::from_slug(&Slug::new("invalid_tp".to_string()).unwrap()).is_err());
970
2
        assert!(TimePeriod::from_slug(&Slug::new("2_1_3_4".to_string()).unwrap()).is_err());
971
2
    }
972

            
973
    #[test]
974
2
    fn encode_hsid() {
975
2
        let b32 = "eweiibe6tdjsdprb4px6rqrzzcsi22m4koia44kc5pcjr7nec2rlxyad";
976
2
        let onion = format!("{b32}.onion");
977
2
        let hsid = HsId::from_str(&onion).unwrap();
978
2
        let hsid_slug = hsid.to_slug().unwrap();
979

            
980
2
        assert_eq!(hsid_slug.to_string(), b32);
981
2
        assert_eq!(hsid, HsId::from_slug(&hsid_slug).unwrap());
982
2
    }
983

            
984
    #[test]
985
2
    fn key_info_builder() {
986
        // A helper to check the extra_info of a `KeyPathInfo`
987
        macro_rules! assert_extra_info_eq {
988
            ($key_info:expr, [$(($k:expr, $v:expr),)*]) => {{
989
                assert_eq!(
990
                    $key_info.extra_info.into_iter().collect_vec(),
991
                    vec![
992
                        $(($k.into(), $v.into()),)*
993
                    ]
994
                );
995
            }}
996
        }
997
2
        let extra_info = vec![("nickname".into(), "bar".into())];
998

            
999
2
        let key_info = KeyPathInfo::builder()
2
            .summary("test summary".into())
2
            .role("KS_vote".to_string())
2
            .set_all_extra_info(extra_info.clone().into_iter())
2
            .build()
2
            .unwrap();
2
        assert_eq!(key_info.extra_info.into_iter().collect_vec(), extra_info);
2
        let key_info = KeyPathInfo::builder()
2
            .summary("test summary".into())
2
            .role("KS_vote".to_string())
2
            .set_all_extra_info(extra_info.clone().into_iter())
2
            .extra_info("type", "service")
2
            .extra_info("time period", "100")
2
            .build()
2
            .unwrap();
2
        assert_extra_info_eq!(
            key_info,
            [
2
                ("nickname", "bar"),
2
                ("time period", "100"),
2
                ("type", "service"),
            ]
        );
2
        let key_info = KeyPathInfo::builder()
2
            .summary("test summary".into())
2
            .role("KS_vote".to_string())
2
            .extra_info("type", "service")
2
            .extra_info("time period", "100")
2
            .set_all_extra_info(extra_info.clone().into_iter())
2
            .build()
2
            .unwrap();
2
        assert_extra_info_eq!(key_info, [("nickname", "bar"),]);
2
        let key_info = KeyPathInfo::builder()
2
            .summary("test summary".into())
2
            .role("KS_vote".to_string())
2
            .extra_info("type", "service")
2
            .extra_info("time period", "100")
2
            .build()
2
            .unwrap();
2
        assert_extra_info_eq!(key_info, [("time period", "100"), ("type", "service"),]);
2
    }
}