tor_config/
misc.rs

1//! Miscellaneous types used in configuration
2//!
3//! This module contains types that need to be shared across various crates
4//! and layers, but which don't depend on specific elements of the Tor system.
5
6use std::borrow::Cow;
7use std::fmt::Debug;
8
9use serde::{Deserialize, Serialize};
10use strum::{Display, EnumString, IntoStaticStr};
11
12/// Boolean, but with additional `"auto"` option
13//
14// This slightly-odd interleaving of derives and attributes stops rustfmt doing a daft thing
15#[derive(Clone, Copy, Hash, Debug, Default, Ord, PartialOrd, Eq, PartialEq)]
16#[allow(clippy::exhaustive_enums)] // we will add variants very rarely if ever
17#[derive(Serialize, Deserialize)]
18#[serde(try_from = "BoolOrAutoSerde", into = "BoolOrAutoSerde")]
19pub enum BoolOrAuto {
20    #[default]
21    /// Automatic
22    Auto,
23    /// Explicitly specified
24    Explicit(bool),
25}
26
27impl BoolOrAuto {
28    /// Returns the explicitly set boolean value, or `None`
29    ///
30    /// ```
31    /// use tor_config::BoolOrAuto;
32    ///
33    /// fn calculate_default() -> bool { //...
34    /// # false }
35    /// let bool_or_auto: BoolOrAuto = // ...
36    /// # Default::default();
37    /// let _: bool = bool_or_auto.as_bool().unwrap_or_else(|| calculate_default());
38    /// ```
39    pub fn as_bool(self) -> Option<bool> {
40        match self {
41            BoolOrAuto::Auto => None,
42            BoolOrAuto::Explicit(v) => Some(v),
43        }
44    }
45}
46
47/// How we (de) serialize a [`BoolOrAuto`]
48#[derive(Serialize, Deserialize)]
49#[serde(untagged)]
50enum BoolOrAutoSerde {
51    /// String (in snake case)
52    String(Cow<'static, str>),
53    /// bool
54    Bool(bool),
55}
56
57impl From<BoolOrAuto> for BoolOrAutoSerde {
58    fn from(boa: BoolOrAuto) -> BoolOrAutoSerde {
59        use BoolOrAutoSerde as BoAS;
60        boa.as_bool()
61            .map(BoAS::Bool)
62            .unwrap_or_else(|| BoAS::String("auto".into()))
63    }
64}
65
66/// Boolean or `"auto"` configuration is invalid
67#[derive(thiserror::Error, Debug, Clone)]
68#[non_exhaustive]
69#[error(r#"Invalid value, expected boolean or "auto""#)]
70pub struct InvalidBoolOrAuto {}
71
72impl TryFrom<BoolOrAutoSerde> for BoolOrAuto {
73    type Error = InvalidBoolOrAuto;
74
75    fn try_from(pls: BoolOrAutoSerde) -> Result<BoolOrAuto, Self::Error> {
76        use BoolOrAuto as BoA;
77        use BoolOrAutoSerde as BoAS;
78        Ok(match pls {
79            BoAS::Bool(v) => BoA::Explicit(v),
80            BoAS::String(s) if s == "false" => BoA::Explicit(false),
81            BoAS::String(s) if s == "true" => BoA::Explicit(true),
82            BoAS::String(s) if s == "auto" => BoA::Auto,
83            _ => return Err(InvalidBoolOrAuto {}),
84        })
85    }
86}
87
88/// A macro that implements [`NotAutoValue`] for your type.
89///
90/// This macro generates:
91///   * a [`NotAutoValue`] impl for `ty`
92///   * a test module with a test that ensures "auto" cannot be deserialized as `ty`
93///
94/// ## Example
95///
96/// ```rust
97/// # use tor_config::{impl_not_auto_value, ExplicitOrAuto};
98/// # use serde::{Serialize, Deserialize};
99//  #
100/// #[derive(Serialize, Deserialize)]
101/// struct Foo;
102///
103/// impl_not_auto_value!(Foo);
104///
105/// #[derive(Serialize, Deserialize)]
106/// struct Bar;
107///
108/// fn main() {
109///    let _foo: ExplicitOrAuto<Foo> = ExplicitOrAuto::Auto;
110///
111///    // Using a type that does not implement NotAutoValue is an error:
112///    // let _bar: ExplicitOrAuto<Bar> = ExplicitOrAuto::Auto;
113/// }
114/// ```
115#[macro_export]
116macro_rules! impl_not_auto_value {
117    ($ty:ty) => {
118        $crate::deps::paste! {
119            impl $crate::NotAutoValue for $ty {}
120
121            #[cfg(test)]
122            #[allow(non_snake_case)]
123            mod [<test_not_auto_value_ $ty>] {
124                #[allow(unused_imports)]
125                use super::*;
126
127                #[test]
128                fn [<auto_is_not_a_valid_value_for_ $ty>]() {
129                    let res = $crate::deps::serde_value::Value::String(
130                        "auto".into()
131                    ).deserialize_into::<$ty>();
132
133                    assert!(
134                        res.is_err(),
135                        concat!(
136                            stringify!($ty), " is not a valid NotAutoValue type: ",
137                            "NotAutoValue types should not be deserializable from \"auto\""
138                        ),
139                    );
140                }
141            }
142        }
143    };
144}
145
146/// A serializable value, or auto.
147///
148/// Used for implementing configuration options that can be explicitly initialized
149/// with a placeholder for their "default" value using the
150/// [`Auto`](ExplicitOrAuto::Auto) variant.
151///
152/// Unlike `#[serde(default)] field: T` or `#[serde(default)] field: Option<T>`,
153/// fields of this type can be present in the serialized configuration
154/// without being assigned a concrete value.
155///
156/// **Important**: the underlying type must implement [`NotAutoValue`].
157/// This trait should be implemented using the [`impl_not_auto_value`],
158/// and only for types that do not serialize to the same value as the
159/// [`Auto`](ExplicitOrAuto::Auto) variant.
160///
161/// ## Example
162///
163/// In the following serialized TOML config
164///
165/// ```toml
166///  foo = "auto"
167/// ```
168///
169/// `foo` is set to [`Auto`](ExplicitOrAuto::Auto), which indicates the
170/// implementation should use a default (but not necessarily [`Default::default`])
171/// value for the `foo` option.
172///
173/// For example, f field `foo` defaults to `13` if feature `bar` is enabled,
174/// and `9000` otherwise, a configuration with `foo` set to `"auto"` will
175/// behave in the "default" way regardless of which features are enabled.
176///
177/// ```rust,ignore
178/// struct Foo(usize);
179///
180/// impl Default for Foo {
181///     fn default() -> Foo {
182///         if cfg!(feature = "bar") {
183///             Foo(13)
184///         } else {
185///             Foo(9000)
186///         }
187///     }
188/// }
189///
190/// impl Foo {
191///     fn from_explicit_or_auto(foo: ExplicitOrAuto<Foo>) -> Self {
192///         match foo {
193///             // If Auto, choose a sensible default for foo
194///             ExplicitOrAuto::Auto => Default::default(),
195///             ExplicitOrAuto::Foo(foo) => foo,
196///         }
197///     }
198/// }
199///
200/// struct Config {
201///    foo: ExplicitOrAuto<Foo>,
202/// }
203/// ```
204#[derive(Clone, Copy, Hash, Debug, Default, Ord, PartialOrd, Eq, PartialEq)]
205#[allow(clippy::exhaustive_enums)] // we will add variants very rarely if ever
206#[derive(Serialize, Deserialize)]
207pub enum ExplicitOrAuto<T: NotAutoValue> {
208    /// Automatic
209    #[default]
210    #[serde(rename = "auto")]
211    Auto,
212    /// Explicitly specified
213    #[serde(untagged)]
214    Explicit(T),
215}
216
217impl<T: NotAutoValue> ExplicitOrAuto<T> {
218    /// Returns the explicitly set value, or `None`.
219    ///
220    /// ```
221    /// use tor_config::ExplicitOrAuto;
222    ///
223    /// fn calculate_default() -> usize { //...
224    /// # 2 }
225    /// let explicit_or_auto: ExplicitOrAuto<usize> = // ...
226    /// # Default::default();
227    /// let _: usize = explicit_or_auto.into_value().unwrap_or_else(|| calculate_default());
228    /// ```
229    pub fn into_value(self) -> Option<T> {
230        match self {
231            ExplicitOrAuto::Auto => None,
232            ExplicitOrAuto::Explicit(v) => Some(v),
233        }
234    }
235
236    /// Returns a reference to the explicitly set value, or `None`.
237    ///
238    /// Like [`ExplicitOrAuto::into_value`], except it returns a reference to the inner type.
239    pub fn as_value(&self) -> Option<&T> {
240        match self {
241            ExplicitOrAuto::Auto => None,
242            ExplicitOrAuto::Explicit(v) => Some(v),
243        }
244    }
245
246    /// Maps an `ExplicitOrAuto<T>` to an `ExplicitOrAuto<U>` by applying a function to a contained
247    /// value.
248    pub fn map<U: NotAutoValue>(self, f: impl FnOnce(T) -> U) -> ExplicitOrAuto<U> {
249        match self {
250            Self::Auto => ExplicitOrAuto::Auto,
251            Self::Explicit(x) => ExplicitOrAuto::Explicit(f(x)),
252        }
253    }
254}
255
256impl<T> From<T> for ExplicitOrAuto<T>
257where
258    T: NotAutoValue,
259{
260    fn from(x: T) -> Self {
261        Self::Explicit(x)
262    }
263}
264
265/// A marker trait for types that do not serialize to the same value as [`ExplicitOrAuto::Auto`].
266///
267/// **Important**: you should not implement this trait manually.
268/// Use the [`impl_not_auto_value`] macro instead.
269///
270/// This trait should be implemented for types that can be stored in [`ExplicitOrAuto`].
271pub trait NotAutoValue {}
272
273/// A helper for calling [`impl_not_auto_value`] for a number of types.
274macro_rules! impl_not_auto_value_for_types {
275    ($($ty:ty)*) => {
276        $(impl_not_auto_value!($ty);)*
277    }
278}
279
280// Implement `NotAutoValue` for various primitive types.
281impl_not_auto_value_for_types!(
282    i8 i16 i32 i64 i128 isize
283    u8 u16 u32 u64 u128 usize
284    f32 f64
285    char
286    bool
287);
288
289use tor_basic_utils::ByteQty;
290impl_not_auto_value!(ByteQty);
291
292// TODO implement `NotAutoValue` for other types too
293
294/// Padding enablement - rough amount of padding requested
295///
296/// Padding is cover traffic, used to help mitigate traffic analysis,
297/// obscure traffic patterns, and impede router-level data collection.
298///
299/// This same enum is used to control padding at various levels of the Tor system.
300/// (TODO: actually we don't do circuit padding yet.)
301//
302// This slightly-odd interleaving of derives and attributes stops rustfmt doing a daft thing
303#[derive(Clone, Copy, Hash, Debug, Ord, PartialOrd, Eq, PartialEq)]
304#[allow(clippy::exhaustive_enums)] // we will add variants very rarely if ever
305#[derive(Serialize, Deserialize)]
306#[serde(try_from = "PaddingLevelSerde", into = "PaddingLevelSerde")]
307#[derive(Display, EnumString, IntoStaticStr)]
308#[strum(serialize_all = "snake_case")]
309#[derive(Default)]
310pub enum PaddingLevel {
311    /// Disable padding completely
312    None,
313    /// Reduced padding (eg for mobile)
314    Reduced,
315    /// Normal padding (the default)
316    #[default]
317    Normal,
318}
319
320/// How we (de) serialize a [`PaddingLevel`]
321#[derive(Serialize, Deserialize)]
322#[serde(untagged)]
323enum PaddingLevelSerde {
324    /// String (in snake case)
325    ///
326    /// We always serialize this way
327    String(Cow<'static, str>),
328    /// bool
329    Bool(bool),
330}
331
332impl From<PaddingLevel> for PaddingLevelSerde {
333    fn from(pl: PaddingLevel) -> PaddingLevelSerde {
334        PaddingLevelSerde::String(<&str>::from(&pl).into())
335    }
336}
337
338/// Padding level configuration is invalid
339#[derive(thiserror::Error, Debug, Clone)]
340#[non_exhaustive]
341#[error("Invalid padding level")]
342struct InvalidPaddingLevel {}
343
344impl TryFrom<PaddingLevelSerde> for PaddingLevel {
345    type Error = InvalidPaddingLevel;
346
347    fn try_from(pls: PaddingLevelSerde) -> Result<PaddingLevel, Self::Error> {
348        Ok(match pls {
349            PaddingLevelSerde::String(s) => {
350                s.as_ref().try_into().map_err(|_| InvalidPaddingLevel {})?
351            }
352            PaddingLevelSerde::Bool(false) => PaddingLevel::None,
353            PaddingLevelSerde::Bool(true) => PaddingLevel::Normal,
354        })
355    }
356}
357
358#[cfg(test)]
359mod test {
360    // @@ begin test lint list maintained by maint/add_warning @@
361    #![allow(clippy::bool_assert_comparison)]
362    #![allow(clippy::clone_on_copy)]
363    #![allow(clippy::dbg_macro)]
364    #![allow(clippy::mixed_attributes_style)]
365    #![allow(clippy::print_stderr)]
366    #![allow(clippy::print_stdout)]
367    #![allow(clippy::single_char_pattern)]
368    #![allow(clippy::unwrap_used)]
369    #![allow(clippy::unchecked_duration_subtraction)]
370    #![allow(clippy::useless_vec)]
371    #![allow(clippy::needless_pass_by_value)]
372    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
373    use super::*;
374
375    #[derive(Debug, Default, Deserialize, Serialize)]
376    struct TestConfigFile {
377        #[serde(default)]
378        something_enabled: BoolOrAuto,
379
380        #[serde(default)]
381        padding: PaddingLevel,
382
383        #[serde(default)]
384        auto_or_usize: ExplicitOrAuto<usize>,
385
386        #[serde(default)]
387        auto_or_bool: ExplicitOrAuto<bool>,
388    }
389
390    #[test]
391    fn bool_or_auto() {
392        use BoolOrAuto as BoA;
393
394        let chk = |pl, s| {
395            let tc: TestConfigFile = toml::from_str(s).expect(s);
396            assert_eq!(pl, tc.something_enabled, "{:?}", s);
397        };
398
399        chk(BoA::Auto, "");
400        chk(BoA::Auto, r#"something_enabled = "auto""#);
401        chk(BoA::Explicit(true), r#"something_enabled = true"#);
402        chk(BoA::Explicit(true), r#"something_enabled = "true""#);
403        chk(BoA::Explicit(false), r#"something_enabled = false"#);
404        chk(BoA::Explicit(false), r#"something_enabled = "false""#);
405
406        let chk_e = |s| {
407            let tc: Result<TestConfigFile, _> = toml::from_str(s);
408            let _ = tc.expect_err(s);
409        };
410
411        chk_e(r#"something_enabled = 1"#);
412        chk_e(r#"something_enabled = "unknown""#);
413        chk_e(r#"something_enabled = "True""#);
414    }
415
416    #[test]
417    fn padding_level() {
418        use PaddingLevel as PL;
419
420        let chk = |pl, s| {
421            let tc: TestConfigFile = toml::from_str(s).expect(s);
422            assert_eq!(pl, tc.padding, "{:?}", s);
423        };
424
425        chk(PL::None, r#"padding = "none""#);
426        chk(PL::None, r#"padding = false"#);
427        chk(PL::Reduced, r#"padding = "reduced""#);
428        chk(PL::Normal, r#"padding = "normal""#);
429        chk(PL::Normal, r#"padding = true"#);
430        chk(PL::Normal, "");
431
432        let chk_e = |s| {
433            let tc: Result<TestConfigFile, _> = toml::from_str(s);
434            let _ = tc.expect_err(s);
435        };
436
437        chk_e(r#"padding = 1"#);
438        chk_e(r#"padding = "unknown""#);
439        chk_e(r#"padding = "Normal""#);
440    }
441
442    #[test]
443    fn explicit_or_auto() {
444        use ExplicitOrAuto as EOA;
445
446        let chk = |eoa: EOA<usize>, s| {
447            let tc: TestConfigFile = toml::from_str(s).expect(s);
448            assert_eq!(
449                format!("{:?}", eoa),
450                format!("{:?}", tc.auto_or_usize),
451                "{:?}",
452                s
453            );
454        };
455
456        chk(EOA::Auto, r#"auto_or_usize = "auto""#);
457        chk(EOA::Explicit(20), r#"auto_or_usize = 20"#);
458
459        let chk_e = |s| {
460            let tc: Result<TestConfigFile, _> = toml::from_str(s);
461            let _ = tc.expect_err(s);
462        };
463
464        chk_e(r#"auto_or_usize = """#);
465        chk_e(r#"auto_or_usize = []"#);
466        chk_e(r#"auto_or_usize = {}"#);
467
468        let chk = |eoa: EOA<bool>, s| {
469            let tc: TestConfigFile = toml::from_str(s).expect(s);
470            assert_eq!(
471                format!("{:?}", eoa),
472                format!("{:?}", tc.auto_or_bool),
473                "{:?}",
474                s
475            );
476        };
477
478        // ExplicitOrAuto<bool> works just like BoolOrAuto
479        chk(EOA::Auto, r#"auto_or_bool = "auto""#);
480        chk(EOA::Explicit(false), r#"auto_or_bool = false"#);
481
482        chk_e(r#"auto_or_bool= "not bool or auto""#);
483
484        let mut config = TestConfigFile::default();
485        let toml = toml::to_string(&config).unwrap();
486        assert_eq!(
487            toml,
488            r#"something_enabled = "auto"
489padding = "normal"
490auto_or_usize = "auto"
491auto_or_bool = "auto"
492"#
493        );
494
495        config.auto_or_bool = ExplicitOrAuto::Explicit(true);
496        let toml = toml::to_string(&config).unwrap();
497        assert_eq!(
498            toml,
499            r#"something_enabled = "auto"
500padding = "normal"
501auto_or_usize = "auto"
502auto_or_bool = true
503"#
504        );
505    }
506}