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
//! `tor-config`: Tools for configuration management in Arti
//!
//! # Overview
//!
//! This crate is part of
//! [Arti](https://gitlab.torproject.org/tpo/core/arti/), a project to
//! implement [Tor](https://www.torproject.org/) in Rust.
//!
//! It provides types for handling configuration values,
//! and general machinery for configuration management.
//!
//! # Configuration in Arti
//!
//! The configuration for the `arti` command line program,
//! and other programs which embed Arti reusing the configuration machinery,
//! works as follows:
//!
//! 1. We use [`tor_config::ConfigurationSources`](ConfigurationSources)
//! to enumerate the various places
//! where configuration information needs to come from,
//! and configure how they are to be read.
//! `arti` uses [`ConfigurationSources::from_cmdline`].
//!
//! 2. [`ConfigurationSources::load`] actually *reads* all of these sources,
//! parses them (eg, as TOML files),
//! and returns a [`config::Config`].
//! This is a tree-structured dynamically typed data structure,
//! mirroring the input configuration structure, largely unvalidated,
//! and containing everything in the input config sources.
//!
//! 3. We call one of the [`tor_config::resolve`](resolve) family.
//! This maps the input configuration data to concrete `ConfigBuilder `s
//! for the configuration consumers within the program.
//! (For `arti`, that's `TorClientConfigBuilder` and `ArtiBuilder`).
//! This mapping is done using the `Deserialize` implementations on the `Builder`s.
//! `resolve` then calls the `build()` method on each of these parts of the configuration
//! which applies defaults and validates the resulting configuration.
//!
//! It is important to call `resolve` *once* for *all* the configuration consumers,
//! so that it sees a unified view of which config settings in the input
//! were unrecognized, and therefore may need to be reported to the user.
//! See the example in the [`load`] module documentation.
//!
//! 4. The resulting configuration objects (eg, `TorClientConfig`, `ArtiConfig`)
//! are provided to the code that must use them (eg, to make a `TorClient`).
//!
//! See the
//! [`tor_config::load` module-level documentation](load).
//! for an example.
//!
//! # ⚠ Stability Warning ⚠
//!
//! The design of this crate, and of the configuration system for
//! Arti, is likely to change significantly before the release of Arti
//! 1.0.0. For more information see ticket [#285].
//!
//! [#285]: https://gitlab.torproject.org/tpo/core/arti/-/issues/285
// @@ begin lint list maintained by maint/add_warning @@
#![deny(missing_docs)]
#![warn(noop_method_call)]
#![deny(unreachable_pub)]
#![warn(clippy::all)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::cargo_common_metadata)]
#![deny(clippy::cast_lossless)]
#![deny(clippy::checked_conversions)]
#![warn(clippy::cognitive_complexity)]
#![deny(clippy::debug_assert_with_mut_call)]
#![deny(clippy::exhaustive_enums)]
#![deny(clippy::exhaustive_structs)]
#![deny(clippy::expl_impl_clone_on_copy)]
#![deny(clippy::fallible_impl_from)]
#![deny(clippy::implicit_clone)]
#![deny(clippy::large_stack_arrays)]
#![warn(clippy::manual_ok_or)]
#![deny(clippy::missing_docs_in_private_items)]
#![deny(clippy::missing_panics_doc)]
#![warn(clippy::needless_borrow)]
#![warn(clippy::needless_pass_by_value)]
#![warn(clippy::option_option)]
#![warn(clippy::rc_buffer)]
#![deny(clippy::ref_option_ref)]
#![warn(clippy::semicolon_if_nothing_returned)]
#![warn(clippy::trait_duplication_in_bounds)]
#![deny(clippy::unnecessary_wraps)]
#![warn(clippy::unseparated_literal_suffix)]
#![deny(clippy::unwrap_used)]
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
pub mod cmdline;
mod err;
pub mod list_builder;
pub mod load;
mod mut_cfg;
mod path;
pub mod sources;
pub use cmdline::CmdLine;
pub use config as config_crate;
pub use educe;
pub use err::{ConfigBuildError, ReconfigureError};
pub use load::{resolve, resolve_ignore_unrecognized, resolve_return_unrecognized};
pub use mut_cfg::MutCfg;
pub use paste::paste;
pub use path::{CfgPath, CfgPathError};
pub use serde;
pub use sources::ConfigurationSources;
pub use tor_basic_utils::macro_first_nonempty;
/// Rules for reconfiguring a running Arti instance.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum Reconfigure {
/// Perform no reconfiguration unless we can guarantee that all changes will be successful.
AllOrNothing,
/// Try to reconfigure as much as possible; warn on fields that we cannot reconfigure.
WarnOnFailures,
/// Don't reconfigure anything: Only check whether we can guarantee that all changes will be successful.
CheckAllOrNothing,
}
impl Reconfigure {
/// Called when we see a disallowed attempt to change `field`: either give a ReconfigureError,
/// or warn and return `Ok(())`, depending on the value of `self`.
pub fn cannot_change<S: AsRef<str>>(self, field: S) -> Result<(), ReconfigureError> {
match self {
Reconfigure::AllOrNothing | Reconfigure::CheckAllOrNothing => {
Err(ReconfigureError::CannotChange {
field: field.as_ref().to_owned(),
})
}
Reconfigure::WarnOnFailures => {
tracing::warn!("Cannot change {} on a running client.", field.as_ref());
Ok(())
}
}
}
}
/// Resolves an `Option<Option<T>>` (in a builder) into an `Option<T>`
///
/// * If the input is `None`, this indicates that the user did not specify a value,
/// and we therefore use `def` to obtain the default value.
///
/// * If the input is `Some(None)`, or `Some(Some(Default::default()))`,
/// the user has explicitly specified that this config item should be null/none/nothing,
/// so we return `None`.
///
/// * Otherwise the user provided an actual value, and we return `Some` of it.
///
/// See <https://gitlab.torproject.org/tpo/core/arti/-/issues/488>
///
/// For consistency with other APIs in Arti, when using this,
/// do not pass `setter(strip_option)` to derive_builder.
///
/// # ⚠ Stability Warning ⚠
///
/// We hope to significantly change this so that it is an method in an extension trait.
/// We may also make it able to support settings where the special "no such thing" value is
/// not `T::Default`.
//
// This is an annoying AOI right now because you have to write things like
// #[builder(field(build = r#"tor_config::resolve_option(&self.dns_port, || None)"#))]
// pub(crate) dns_port: Option<u16>,
// which recapitulates the field name. That is very much a bug hazard (indeed, in an
// early version of some of this code I perpetrated precisely that bug).
// Fixing this involves a derive_builder feature.
pub fn resolve_option<T, DF>(input: &Option<Option<T>>, def: DF) -> Option<T>
where
T: Clone + Default + PartialEq,
DF: FnOnce() -> Option<T>,
{
match input {
None => def(),
Some(None) => None,
Some(Some(v)) if v == &T::default() => None,
Some(Some(v)) => Some(v.clone()),
}
}
/// Defines standard impls for a struct with a `Builder`, incl `Default`
///
/// **Use this.** Do not `#[derive(Builder, Default)]`. That latter approach would produce
/// wrong answers if builder attributes are used to specify non-`Default` default values.
///
/// # Input syntax
///
/// ```
/// use derive_builder::Builder;
/// use serde::{Deserialize, Serialize};
/// use tor_config::impl_standard_builder;
/// use tor_config::ConfigBuildError;
///
/// #[derive(Debug, Builder, Clone, Eq, PartialEq)]
/// #[builder(derive(Serialize, Deserialize, Debug))]
/// #[builder(build_fn(error = "ConfigBuildError"))]
/// struct SomeConfigStruct { }
/// impl_standard_builder! { SomeConfigStruct }
///
/// #[derive(Debug, Builder, Clone, Eq, PartialEq)]
/// struct UnusualStruct { }
/// impl_standard_builder! { UnusualStruct: !Deserialize + !Builder }
/// ```
///
/// # Requirements
///
/// `$Config`'s builder must have default values for all the fields,
/// or this macro-generated self-test will fail.
/// This should be OK for all principal elements of our configuration.
///
/// `$ConfigBuilder` must have an appropriate `Deserialize` impl.
///
/// # Options
///
/// * `!Default` suppresses the `Default` implementation, and the corresponding tests.
/// This should be done within Arti's configuration only for sub-structures which
/// contain mandatory fields (and are themselves optional).
///
/// * `!Deserialize` suppresses the test case involving `Builder: Deserialize`.
/// This should not be done for structs which are part of Arti's configuration,
/// but can be appropriate for other types that use [`derive_builder`].
///
/// * `!Builder` suppresses the impl of the [`tor_config::load::Builder`](load::Builder) trait
/// This will be necessary if the error from the builder is not [`ConfigBuildError`].
///
/// # Generates
///
/// * `impl Default for $Config`
/// * `impl Builder for $ConfigBuilder`
/// * a self-test that the `Default` impl actually works
/// * a test that the `Builder` can be deserialized from an empty [`config::Config`],
/// and then built, and that the result is the same as the ordinary default.
//
// The implementation munches fake "trait bounds" (`: !Deserialize + !Wombat ...`) off the RHS.
// We're going to add at least one more option.
//
// When run with `!Default`, this only generates a `builder` impl and an impl of
// the `Resolvable` trait which probably won't be used anywhere. That may seem
// like a poor tradeoff (much fiddly macro code to generate a trivial function in
// a handful of call sites). However, this means that `impl_standard_builder!`
// can be used in more places. That sets a good example: always use the macro.
//
// That is a good example because we want `impl_standard_builder!` to be
// used elsewhere because it generates necessary tests of properties
// which might otherwise be violated. When adding code, people add according to the
// patterns they see.
//
// (We, sadly, don't have a good way to *ensure* use of `impl_standard_builder`.)
#[macro_export]
macro_rules! impl_standard_builder {
// Convert the input into the "being processed format":
{
$Config:ty $(: $($options:tt)* )?
} => { $crate::impl_standard_builder!{
// ^Being processed format:
@ ( Builder )
( default )
( try_deserialize ) $Config : $( $( $options )* )?
// ~~~~~~~~~~~~~~~ ^^^^^^^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// present iff not !Builder, !Default
// present iff not !Default
// present iff not !Deserialize type always present options yet to be parsed
} };
// If !Deserialize is the next option, implement it by making $try_deserialize absent
{
@ ( $($Builder :ident)? )
( $($default :ident)? )
( $($try_deserialize:ident)? ) $Config:ty : $(+)? !Deserialize $( $options:tt )*
} => { $crate::impl_standard_builder!{
@ ( $($Builder )? )
( $($default )? )
( ) $Config : $( $options )*
} };
// If !Builder is the next option, implement it by making $Builder absent
{
@ ( $($Builder :ident)? )
( $($default :ident)? )
( $($try_deserialize:ident)? ) $Config:ty : $(+)? !Builder $( $options:tt )*
} => { $crate::impl_standard_builder!{
@ ( )
( $($default )? )
( $($try_deserialize )? ) $Config : $( $options )*
} };
// If !Default is the next option, implement it by making $default absent
{
@ ( $($Builder :ident)? )
( $($default :ident)? )
( $($try_deserialize:ident)? ) $Config:ty : $(+)? !Default $( $options:tt )*
} => { $crate::impl_standard_builder!{
@ ( $($Builder )? )
( )
( $($try_deserialize )? ) $Config : $( $options )*
} };
// Having parsed all options, produce output:
{
@ ( $($Builder :ident)? )
( $($default :ident)? )
( $($try_deserialize:ident)? ) $Config:ty : $(+)?
} => { $crate::paste!{
impl $Config {
/// Returns a fresh, default, builder
pub fn builder() -> [< $Config Builder >] {
Default::default()
}
}
$( // expands iff there was $default, which is always default
impl Default for $Config {
fn $default() -> Self {
// unwrap is good because one of the test cases above checks that it works!
[< $Config Builder >]::default().build().unwrap()
}
}
)?
$( // expands iff there was $Builder, which is always Builder
impl $crate::load::$Builder for [< $Config Builder >] {
type Built = $Config;
fn build(&self) -> std::result::Result<$Config, $crate::ConfigBuildError> {
[< $Config Builder >]::build(self)
}
}
)?
#[test]
#[allow(non_snake_case)]
fn [< test_impl_Default_for_ $Config >] () {
#[allow(unused_variables)]
let def = None::<$Config>;
$( // expands iff there was $default, which is always default
let def = Some($Config::$default());
)?
if let Some(def) = def {
$( // expands iff there was $try_deserialize, which is always try_deserialize
let empty_config = $crate::config_crate::Config::builder().build().unwrap();
let builder: [< $Config Builder >] = empty_config.$try_deserialize().unwrap();
let from_empty = builder.build().unwrap();
assert_eq!(def, from_empty);
)*
}
}
} };
}
#[cfg(test)]
#[allow(clippy::unwrap_used)] // why is this not the default in tests
mod test {
use super::*;
use crate as tor_config;
use derive_builder::Builder;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tracing_test::traced_test;
#[test]
#[traced_test]
fn reconfigure_helpers() {
let how = Reconfigure::AllOrNothing;
let err = how.cannot_change("the_laws_of_physics").unwrap_err();
assert_eq!(
err.to_string(),
"Cannot change the_laws_of_physics on a running client.".to_owned()
);
let how = Reconfigure::WarnOnFailures;
let ok = how.cannot_change("stuff");
assert!(ok.is_ok());
assert!(logs_contain("Cannot change stuff on a running client."));
}
#[test]
#[rustfmt::skip] // autoformatting obscures the regular structure
fn resolve_option_test() {
#[derive(Debug, Clone, Builder, Eq, PartialEq)]
#[builder(build_fn(error = "ConfigBuildError"))]
#[builder(derive(Debug, Serialize, Deserialize, Eq, PartialEq))]
struct TestConfig {
#[builder(field(build = r#"tor_config::resolve_option(&self.none, || None)"#))]
none: Option<u32>,
#[builder(field(build = r#"tor_config::resolve_option(&self.four, || Some(4))"#))]
four: Option<u32>,
}
// defaults
{
let builder_from_json: TestConfigBuilder = serde_json::from_value(
json!{ { } }
).unwrap();
let builder_from_methods = TestConfigBuilder::default();
assert_eq!(builder_from_methods, builder_from_json);
assert_eq!(builder_from_methods.build().unwrap(),
TestConfig { none: None, four: Some(4) });
}
// explicit positive values
{
let builder_from_json: TestConfigBuilder = serde_json::from_value(
json!{ { "none": 123, "four": 456 } }
).unwrap();
let mut builder_from_methods = TestConfigBuilder::default();
builder_from_methods.none(Some(123));
builder_from_methods.four(Some(456));
assert_eq!(builder_from_methods, builder_from_json);
assert_eq!(builder_from_methods.build().unwrap(),
TestConfig { none: Some(123), four: Some(456) });
}
// explicit "null" values
{
let builder_from_json: TestConfigBuilder = serde_json::from_value(
json!{ { "none": 0, "four": 0 } }
).unwrap();
let mut builder_from_methods = TestConfigBuilder::default();
builder_from_methods.none(Some(0));
builder_from_methods.four(Some(0));
assert_eq!(builder_from_methods, builder_from_json);
assert_eq!(builder_from_methods.build().unwrap(),
TestConfig { none: None, four: None });
}
// explicit None (API only, serde can't do this for Option)
{
let mut builder_from_methods = TestConfigBuilder::default();
builder_from_methods.none(None);
builder_from_methods.four(None);
assert_eq!(builder_from_methods.build().unwrap(),
TestConfig { none: None, four: None });
}
}
}